package com.hanhai.material.device.utils.kingdee;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hanhai.material.common.result.KingdeeResult;
import com.hanhai.material.common.result.Result;
import com.hanhai.material.common.result.ResultTool;
import com.hanhai.material.device.entity.*;
import com.hanhai.material.device.model.pick.PickData;
import com.hanhai.material.device.service.*;
import com.hanhai.material.utils.redis.RedisUtil;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;

import static com.hanhai.material.device.entity.table.SysBadRecordTableDef.SYS_BAD_RECORD;
import static com.hanhai.material.device.entity.table.SysBomTableDef.SYS_BOM;
import static com.hanhai.material.device.entity.table.SysMachinePlcTableDef.SYS_MACHINE_PLC;
import static com.hanhai.material.device.entity.table.SysPlcTableDef.SYS_PLC;
import static com.hanhai.material.device.entity.table.SysProductRecordShiftTableDef.SYS_PRODUCT_RECORD_SHIFT;
import static com.hanhai.material.device.entity.table.SysProductRecordTableDef.SYS_PRODUCT_RECORD;
import static com.hanhai.material.device.entity.table.SysWeightPlcTableDef.SYS_WEIGHT_PLC;
import static com.hanhai.material.device.entity.table.SysWorkPlanTableDef.SYS_WORK_PLAN;
import static com.hanhai.material.utils.TimeUtils.fromDateToString;
import static com.mybatisflex.core.query.QueryMethods.*;

@Component
@Log4j2
@Lazy
public class AsyncTask {

    @Autowired
    ParamsanaService paramsanaService;
    @Autowired
    ParamsstatusService paramsstatusService;
    @Autowired
    ParamsupService paramsupService;
    @Autowired
    ParamsdownService paramsdownService;
    @Autowired
    SysMachinePlcService sysMachinePlcService;
    @Autowired
    SysPlcService sysPlcService;
    @Autowired
    RedisUtil redisUtil;
    @Value("${plc.redis.key.prefix}")
    private String keyPrefix;

    public String getSid() {
        String username = "schanhai";
        String password = "Hh123456.";
        RestTemplate restTemplate = new RestTemplate();
        String baseUrl = "https://api.123321yun.com/api/user/login/?username=%s&password=%s";
        String url = String.format(baseUrl, username, password);
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        headers.setContentType(type);
//        headers.set("Authorization", authorization);
        HttpEntity httpEntity = new HttpEntity<>(headers);
        ResponseEntity<Object> responseEntity = restTemplate.postForEntity(url, httpEntity, Object.class);
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(responseEntity.getBody());
        System.out.println("JSON:" + jsonObject);
        String sid = jsonObject.getString("data");
        this.redisUtil.set("sid", sid, 25 * 60);
        return sid;
    }


    @Async("taskExecutor")
    public void tesTask(SysProductRecord sysProductRecord, int i, CountDownLatch countDownLatch) throws IOException {
        log.error("多线程生产的机台{}：{}", i, sysProductRecord);
        SysMachinePlc sysMachinePlc = sysProductRecord.getSysMachinePlc();
        if (sysMachinePlc != null) {
            String sid = getSid();
            System.out.println("Sid:" + sid);
            RestTemplate restTemplate = new RestTemplate();
            String plcDeviceId = sysMachinePlc.getPlcDeviceId();
            String baseUrl = "https://api.123321yun.com/device/ex/getDetail?deviceId=%s";
            String url = String.format(baseUrl, plcDeviceId);
            System.out.println("Url:" + url);
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
            headers.setContentType(type);
            headers.set("__sid", sid);
            HttpEntity httpEntity = new HttpEntity<>(headers);
            ResponseEntity<Object> responseEntity = restTemplate.postForEntity(url, httpEntity, Object.class);
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(responseEntity.getBody());
            System.out.println("Result:" + jsonObject);
            long sleepTime = 10;
            if (jsonObject.getString("code").equals("200.0")) {
                Date date = new Date();
                try {
                    SysPlc sysPlc = jsonObject.getObject("data", SysPlc.class);
                    sysPlc.setCreateTime(date);
                    sysPlc.setPlcDeviceId(plcDeviceId);
                    sysPlc.setMachineName(sysMachinePlc.getMachineName());
                    sysPlc.setMachineArea(sysMachinePlc.getMachineArea());
                    sysPlc.setProductRecordId(sysMachinePlc.getProductRecordId());
                    sysPlc.setWorkPlanId(sysProductRecord.getWorkPlanId());
                    sysPlc.setProductRecordId(sysProductRecord.getId());
                    JSONArray jsonObject1 = JSON.parseArray(sysPlc.getParamsUp());
                    boolean isGet1 = false;
                    boolean isGet2 = false;
                    boolean isGet3 = false;
                    for (Object object : jsonObject1) {
                        Paramsup paramsup = JSONObject.parseObject(JSONObject.toJSONString(object), Paramsup.class);
                        if (paramsup.getName().equals("当班产量")) {
                            isGet1 = true;
                            sysPlc.setShiftNum(Double.parseDouble(paramsup.getValue()));
                        }
                        if (paramsup.getName().equals("当模产量")) {
                            isGet2 = true;
                            sysPlc.setModeNum(Double.parseDouble(paramsup.getValue()));
                        }
                        if (paramsup.getName().equals("平均周期")) {
                            isGet3 = true;
                            try {
                                sleepTime = (long) (Double.parseDouble(paramsup.getValue()) * 1000 * 60);
                                if (sleepTime <= 100) {
                                    sleepTime = 6000;
                                }
                                sysPlc.setAveragePeriod(sleepTime);
                            } catch (Exception e) {

                            }
                        }
                        if (isGet1 && isGet2 && isGet3) {
                            break;
                        }
                    }
                    if (sysPlc.getShiftNum() == 0) {
                        System.out.println("数量为0");
                        sleepTime = 60000;
                        Thread.sleep(sleepTime);
                    }

                    this.saveParamsStatus(sysPlc);
                    this.saveParamsUp(sysPlc);
                    this.saveParamsDown(sysPlc);
                    this.saveParamsAna(sysPlc);
                    String key = keyPrefix + sysMachinePlc.getMachineName();
                    this.redisUtil.set(key, sysPlc, 6000);
                    sysPlc.setParamsAna(null);
                    sysPlc.setParamsDown(null);
                    sysPlc.setParamsUp(null);
                    sysPlc.setParamsStatus(null);
                    this.sysPlcService.save(sysPlc);


                } catch (Exception exception) {

                }
            }
            this.dataRefresh(sysProductRecord);
        }
        countDownLatch.countDown();
    }

    @Async("taskExecutor")
    public void changeWorkPlan(List<SysProductRecord> sysProductRecordList, CountDownLatch countDownLatch) throws IOException {
        this.exchange3(sysProductRecordList);
        countDownLatch.countDown();
    }

    public void saveParamsStatus(SysPlc sysPlc) {
        List<Paramsstatus> paramsstatusList = JSON.parseArray(sysPlc.getParamsStatus()).toJavaList(Paramsstatus.class);
        log.info("状态信息：{}", paramsstatusList.toString());
        if (paramsstatusList.isEmpty()) {
            return;
        } else {
            for (Paramsstatus paramsstatus : paramsstatusList) {
                paramsstatus.setPlcId(sysPlc.getId());
                paramsstatus.setCreateTime(sysPlc.getCreateTime());
                paramsstatus.setMachineId(sysPlc.getMachineName());
                paramsstatus.setProductRecordId(sysPlc.getProductRecordId());
            }
            this.paramsstatusService.saveBatch(paramsstatusList);
        }
    }

    public void saveParamsUp(SysPlc sysPlc) {
        List<Paramsup> paramsupList = JSON.parseArray(sysPlc.getParamsUp()).toJavaList(Paramsup.class);
        if (paramsupList.isEmpty()) {
            return;
        } else {
            for (Paramsup paramsup : paramsupList) {
                paramsup.setPlcId(sysPlc.getId());
                paramsup.setCreateTime(sysPlc.getCreateTime());
                paramsup.setMachineId(sysPlc.getMachineName());
                paramsup.setProductRecordId(sysPlc.getProductRecordId());
            }
            this.paramsupService.saveBatch(paramsupList);
        }
    }

    public void saveParamsDown(SysPlc sysPlc) {
        List<Paramsdown> paramsdownList = JSON.parseArray(sysPlc.getParamsDown()).toJavaList(Paramsdown.class);
        if (paramsdownList.isEmpty()) {
            return;
        } else {
            for (Paramsdown paramsdown : paramsdownList) {
                paramsdown.setPlcId(sysPlc.getId());
                paramsdown.setCreateTime(sysPlc.getCreateTime());
                paramsdown.setMachineId(sysPlc.getMachineName());
                paramsdown.setProductRecordId(sysPlc.getProductRecordId());
            }
            this.paramsdownService.saveBatch(paramsdownList);
        }
    }

    public void saveParamsAna(SysPlc sysPlc) {
        List<Paramsana> paramsanaList = JSON.parseArray(sysPlc.getParamsAna()).toJavaList(Paramsana.class);
        if (paramsanaList.isEmpty()) {
            return;
        } else {
            for (Paramsana paramsana : paramsanaList) {
                paramsana.setPlcId(sysPlc.getId());
                paramsana.setCreateTime(sysPlc.getCreateTime());
                paramsana.setMachineId(sysPlc.getMachineName());
                paramsana.setProductRecordId(sysPlc.getProductRecordId());
            }
            this.paramsanaService.saveBatch(paramsanaList);
        }
    }

    @Autowired
    SysProductRecordService sysProductRecordService;

    @Autowired
    SysProductRecordShiftService sysProductRecordShiftService;

    @Autowired
    SysBomService sysBomService;

    public void dataRefresh(SysProductRecord sysProductRecord) throws IOException {
        Date startDate = sysProductRecord.getActualStartTime();
        Date endDate = sysProductRecord.getActualEndTime();
        if (endDate == null) {
            endDate = new Date();
        }
        String start = fromDateToString("yyyy-MM-dd HH:mm:ss", startDate);
        String end = fromDateToString("yyyy-MM-dd HH:mm:ss", endDate);
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_PLC.MACHINE_NAME.eq(sysProductRecord.getMachineName()));
        queryWrapper.where(SYS_PLC.CREATE_TIME.between(start, end));
        queryWrapper.select(max(SYS_PLC.MODE_NUM).subtract(min(SYS_PLC.MODE_NUM)).as("mode_num"))
                .select(SYS_PLC.AVERAGE_PERIOD, SYS_PLC.IMG_URL, SYS_PLC.ID, SYS_PLC.CREATE_TIME, SYS_PLC.MACHINE_NAME)
                .select(SYS_PLC.PARAMS_STATUS, SYS_PLC.PARAMS_UP, SYS_PLC.PARAMS_DOWN);
        SysPlc sysPlc = this.sysPlcService.getOne(queryWrapper);
        int badNum = this.getBadNum(sysProductRecord);
        if (sysPlc != null) {
            System.out.println("SysPLC:" + sysPlc.getModeNum());
            double moldNumber = 1;
            if (sysProductRecord.getWorkPlan() != null) {
                moldNumber = sysProductRecord.getWorkPlan().getMoldNumber();
                if (moldNumber < 0) {
                    moldNumber = 1;
                }
            }
            sysProductRecord.setBadNum(badNum);
            double nowProductNum = sysPlc.getModeNum() * moldNumber;

            int totalCount = 0;
            if (nowProductNum < 0) {
                nowProductNum = 0;
            } else {
                try {
                    totalCount = (int) (nowProductNum + sysProductRecord.getNowProductNum());
                } catch (Exception exception) {
                    totalCount = (int) (nowProductNum);
                }
                sysProductRecord.setGoodNum(totalCount);
                sysProductRecord.setGoodNum(totalCount - badNum);
                sysProductRecord.setTotalCount(totalCount);
            }

            this.sysProductRecordService.updateById(sysProductRecord);
        } else {
            double moldNumber = 1;
            if (sysProductRecord.getWorkPlan() != null) {
                moldNumber = sysProductRecord.getWorkPlan().getMoldNumber();
                if (moldNumber < 0) {
                    moldNumber = 1;
                }
            }

            double nowProductNum = sysProductRecord.getNowProductNum() * moldNumber;
            sysProductRecord.setTotalCount((int) nowProductNum);
            this.sysProductRecordService.updateById(sysProductRecord);
        }
    }


    @Autowired
    SysWorkPlanService sysWorkPlanService;


    public Result<?> exchange3(List<SysProductRecord> sysProductRecordList) throws IOException {
        for (SysProductRecord sysProductRecord : sysProductRecordList) {

            log.error("WORK:{}", JSONObject.toJSONString(sysProductRecord));
            LocalDate localDate = LocalDate.now();
            LocalDateTime localDateTime = localDate.atTime(0, 0, 0);
            Date startTime = Date.from(localDate.atTime(8, 0, 0).atZone(ZoneId.systemDefault()).toInstant());
            String summary = "手动切换";
            String machineName = sysProductRecord.getMachineName();
            /*查询后续排产工单*/
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.where(SYS_WORK_PLAN.PRODUCT_STATUS.eq(1));
            queryWrapper.where(SYS_WORK_PLAN.MACHINE_NAME.eq(machineName));
            queryWrapper.where(SYS_WORK_PLAN.PLAN_END_TIME.ge(localDateTime));
            queryWrapper.where(SYS_WORK_PLAN.WORK_PLAN_ID.ne(sysProductRecord.getWorkPlanId()));
            queryWrapper.orderBy(SYS_WORK_PLAN.WORK_PLAN_ID, true);
            if (sysProductRecord.getWorkPlan().isMoldSame()) {

            } else {
                queryWrapper.limit(1);
            }
            log.error("SQL:{}", queryWrapper.toSQL());
            List<SysWorkPlan> workPlanList = this.sysWorkPlanService.list(queryWrapper);
            for (SysWorkPlan workPlan : workPlanList) {
                queryWrapper = QueryWrapper.create();
                queryWrapper.where(SYS_BOM.PRODUCT_ICMO_ID.eq(workPlan.getInterId()));
                queryWrapper.orderBy(SYS_BOM.ID, false);
                queryWrapper.limit(1);
                SysBom bom = this.sysBomService.getOne(queryWrapper);
                if (bom != null) {
                    workPlan.setBom(bom);
                }

            }
            log.error("WORKPLANLIST:{}", workPlanList);
            /*没有工单继续生产当前工单*/
            if (workPlanList.isEmpty()) {
                log.error("暂无工单");
                sysProductRecord.setContinue(true);
                sysProductRecord.setNormal(true);
                sysProductRecord.setOver(true);
                sysProductRecord.setStart(true);
                this.sysProductRecordService.updateById(sysProductRecord);
                return ResultTool.fail("暂无手动切换");
            } else {
                if (workPlanList.size() == 1) {
                    /*有工单则将当前生产工单关闭，切换到最近计划开始时间的工单*/
                    SysWorkPlan oldWorkPlan = this.sysWorkPlanService.getById(sysProductRecord.getWorkPlanId());
                    queryWrapper = QueryWrapper.create();
                    queryWrapper.where(SYS_BOM.PRODUCT_ICMO_ID.eq(oldWorkPlan.getInterId()));
                    queryWrapper.orderBy(SYS_BOM.ID, false);
                    queryWrapper.limit(1);
                    SysBom bom = this.sysBomService.getOne(queryWrapper);
                    if (bom != null) {
                        oldWorkPlan.setBom(bom);
                    }

                    sysProductRecord.setNormal(false);
                    sysProductRecord.setOver(false);
                    sysProductRecord.setContinue(false);
                    sysProductRecord.setSummary(summary);
                    sysProductRecord.setActualEndTime(new Date());
                    sysProductRecord.setEntry(true);
                    /*有电子称*/
                    if (sysProductRecord.isHasWeight()) {
                        queryWrapper = QueryWrapper.create();
                        queryWrapper.where(SYS_MACHINE_PLC.MACHINE_NAME.eq(sysProductRecord.getMachineName()));
//                    double weight = sysProductRecord.getEndWeight1().doubleValue();
                        SysMachinePlc sysMachinePlc = this.sysMachinePlcService.getOne(queryWrapper);
                        if (sysMachinePlc != null) {
                            sysProductRecord = this.getWeightDataEnd(sysMachinePlc, sysProductRecord);

                        } else {
                            sysProductRecord.setTwoWeight(false);
                            sysProductRecord.setHasWeight(false);
                        }

                    } else {
                        sysProductRecord.setTwoWeight(false);
                        sysProductRecord.setHasWeight(false);
                    }
                    sysProductRecord.setEndUserName("SYSTEM1");
                    sysProductRecord.setEndUserId("SYSTEM1");
//                    boolean result = true;
                    /*更新当前生产记录状态*/
                    boolean result = sysProductRecordService.updateById(sysProductRecord);
                    if (result) {
                        oldWorkPlan.setEnd(true);
                        /*更新当前生产工单状态*/
                        result = this.sysWorkPlanService.updateById(oldWorkPlan);
//                        result = true;
                        if (result) {
                            SysWorkPlan newWorkPlan = null;
//                    newWorkPlan = workPlanList.get(0);
                            /*判断当前工单是否在生产*/
                            for (SysWorkPlan sysWorkPlan : workPlanList) {
                                queryWrapper = QueryWrapper.create();
                                queryWrapper.where(SYS_PRODUCT_RECORD.WORK_PLAN_ID.eq(sysWorkPlan.getWorkPlanId()));
                                queryWrapper.where(SYS_PRODUCT_RECORD.IS_NORMAL.eq(true));
                                queryWrapper.where(SYS_PRODUCT_RECORD.ACTUAL_START_TIME.isNotNull(true));
                                queryWrapper.where(SYS_PRODUCT_RECORD.ACTUAL_END_TIME.isNull(true));
                                queryWrapper.where(SYS_PRODUCT_RECORD.WORK_SHOP.eq("成型车间").or(SYS_PRODUCT_RECORD.WORK_SHOP.isNull()).or(SYS_PRODUCT_RECORD.WORK_SHOP.eq("")));

                                queryWrapper.limit(1);
                                SysProductRecord productRecord = this.sysProductRecordService.getOne(queryWrapper);
                                if (productRecord == null) {
//                                if (productRecord != null) {
                                    newWorkPlan = sysWorkPlan;
                                    break;
                                }
                            }
                            /*如果在生产，则继续生产当前工单*/
                            if (newWorkPlan != null) {
                                SysProductRecord sysProductRecord1 = new SysProductRecord();
                                Date productDate = new Date();
                                String id = fromDateToString("yyyyMMddHHmm", productDate) + sysProductRecord.getMachineName() + newWorkPlan.getWorkPlanId();
                                sysProductRecord1.setId(UUID.randomUUID().toString());
                                sysProductRecord1.setProductDate(productDate);
                                sysProductRecord1.setContinue(true);
                                sysProductRecord1.setOver(false);
                                sysProductRecord1.setStart(true);
                                sysProductRecord1.setNormal(true);
                                sysProductRecord1.setGoodNum(0);
                                sysProductRecord1.setStart(true);
                                sysProductRecord1.setNormal(true);
                                sysProductRecord1.setEntry(false);
                                sysProductRecord1.setActualStartTime(new Date());
                                sysProductRecord1.setTotalCount(0);
                                sysProductRecord1.setProductName(newWorkPlan.getProductName());
                                sysProductRecord1.setShortName(newWorkPlan.getShortName());
                                sysProductRecord1.setWorkPlanProductNum(newWorkPlan.getProductNum());
                                sysProductRecord1.setWorkPlanId(newWorkPlan.getWorkPlanId());
                                sysProductRecord1.setProductId(newWorkPlan.getProductId());
                                sysProductRecord1.setAuto(true);
                                sysProductRecord1.setMachineArea(sysProductRecord.getMachineArea());
                                sysProductRecord1.setMachineName(sysProductRecord.getMachineName());
                                sysProductRecord1.setExchangeType(newWorkPlan.getExchangeType());
                                LocalDateTime now = LocalDateTime.now();
                                LocalDateTime localDate2 = LocalDateTime.of(now.getYear(), now.getMonthValue(), now.getDayOfMonth(), 20, 0, 0);
                                LocalDateTime localDate1 = LocalDateTime.of(now.getYear(), now.getMonthValue(), now.getDayOfMonth(), 8, 0, 0);
                                if (now.isAfter(localDate2) && now.isBefore(localDate1)) {
                                    sysProductRecord1.setShift("夜班");
                                } else {
                                    sysProductRecord1.setShift("白班");
                                }
                                sysProductRecord1.setWorkPlanId(newWorkPlan.getWorkPlanId());
                                sysProductRecord1.setActualStartTime(new Date());
                                sysProductRecord1.setJobNo("SYSTEM1");
                                sysProductRecord1.setUserName("SYSTEM1");
                                sysProductRecord1.setHasWeight(sysProductRecord.getSysMachinePlc().isHasWeight());
                                sysProductRecord1.setTwoWeight(sysProductRecord.getSysMachinePlc().isHasTwoWeight());
                                if (sysProductRecord.isHasWeight()) {
                                    sysProductRecord1.setStartWeight1(sysProductRecord.getEndWeight1().subtract(BigDecimal.valueOf(13).max(BigDecimal.valueOf(0))));
                                } else {
                                    sysProductRecord1.setStartWeight1(BigDecimal.valueOf(0));
                                }
                                if (sysProductRecord.isTwoWeight()) {
                                    sysProductRecord1.setStartWeight2(sysProductRecord.getEndWeight2().subtract(BigDecimal.valueOf(13).max(BigDecimal.valueOf(0))));
                                } else {
                                    sysProductRecord1.setStartWeight2(BigDecimal.valueOf(0));
                                }
                                sysProductRecord1.setMoldSame(sysProductRecord.isMoldSame());
                                sysProductRecord1.setExchangeType(sysProductRecord.getExchangeType());
                                sysProductRecord1.setPaperBoxNumber(sysProductRecord.getPaperBoxNumber());
                                try{
                                    sysProductRecord1.setQuantity(newWorkPlan.getQuantity());
                                }catch (Exception e){

                                }
                                sysProductRecord1.setBadNum(0);
                                try {
                                    result = this.sysProductRecordService.save(sysProductRecord1);
//                                    result = true;
                                    if (result) {


                                        boolean hasTwoMaterial = false;
                                        List<SysBomChild> oldBomList = this.kingdeeUtils.getPPBOMDetail(oldWorkPlan.getBom().getId()).stream().filter(item -> !item.getMaterialId().startsWith("9.")).collect(Collectors.toList());
                                        log.error("OldBomList:{}", JSONArray.toJSONString(oldBomList));
                                        List<SysBomChild> newBomList = this.kingdeeUtils.getPPBOMDetail(newWorkPlan.getBom().getId()).stream().filter(item -> !item.getMaterialId().startsWith("9.")).collect(Collectors.toList());
                                        log.error("OldBomList:{}", JSONArray.toJSONString(newBomList));

                                        List<String> ids = new ArrayList<>();
                                        ids.add("7.Y13A1A000001");
                                        ids.add("7.Y18A1A000001");
                                        ids.add("7.Y11A1A000349");
                                        ids.add("7.Y13A1A000002");
                                        ids.add("7.Y11A1A100120");
                                        if (newBomList.size() > 0) {
                                            List<String> materialIdList = new ArrayList<>();
                                            newBomList.forEach(newItem -> {
                                                materialIdList.add(newItem.getMaterialId().trim());
                                            });
                                            for (SysBomChild sysBomChild : oldBomList) {
                                                if (materialIdList.contains(sysBomChild.getMaterialId().trim())) {
                                                    sysBomChild.setSame(true);
                                                    int index = materialIdList.indexOf(sysBomChild.getMaterialId().trim());
                                                    sysBomChild.setChildBomChild(newBomList.get(index));
                                                }
                                            }

                                        } else {
                                            oldBomList.forEach(oldItem -> {
                                                oldItem.setSame(false);
                                            });
                                        }

                                        for (SysBomChild sysBomChild : oldBomList) {
                                            if (ids.contains(sysBomChild.getMaterialId())) {
                                                hasTwoMaterial = true;
                                                break;
                                            }
                                        }

                                        double totalYS = 0;//原料标准用量
                                        double totalY = 0;//原料已领数量
                                        double totalGS = 0;//改性标准用量
                                        double totalG = 0;//改性已领数量
                                        double totalS = 0;//总标准用量


                                        double YP = 0;//
                                        double GP = 0;//

                                        SysBomChild sysBomChildY = new SysBomChild();
                                        SysBomChild sysBomChildG = new SysBomChild();
                                        int hasY = 0;
                                        int hasC = 0;
                                        oldBomList = oldBomList.stream().filter(item -> item.getAuxqtyPick().doubleValue() > 0).collect(Collectors.toList());
                                        List<SysBomChild> sysBomChildList = oldBomList.stream().filter(item ->
                                                item.getMaterialId().startsWith("7.Y")
                                                        && (!item.getMaterialId().equals("7.Y11A1A000349")
                                                        && !item.getMaterialId().equals("7.Y13A1A000001")
                                                        && !item.getMaterialId().equals("7.Y18A1A000001")
                                                        && !item.getMaterialId().equals("7.Y13A1A000002")
                                                        && !item.getMaterialId().equals("7.Y11A1A100120")
                                                )).collect(Collectors.toList());
                                        /*判断是否有改性料并添加表四*/
                                        for (SysBomChild sysBomChild : sysBomChildList) {
                                            String materialName = sysBomChild.getMaterialName();
                                            if ((materialName.contains("改性") || materialName.contains("抽粒") || materialName.contains("次料")) && sysBomChild.getAuxqtyPick().doubleValue() > 0) {
                                                totalG += sysBomChild.getHasGetNum();
                                                totalGS = sysBomChild.getStandardNum().doubleValue();
                                                sysBomChild.setG(true);
                                                sysBomChildG = sysBomChild;
                                                hasC++;
                                            } else if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                                hasY++;
                                                sysBomChildY = sysBomChild;
                                                totalY += sysBomChild.getHasGetNum();
                                                totalYS = sysBomChild.getStandardNum().doubleValue();
                                            }
                                            totalS += sysBomChild.getStandardNum().doubleValue();
                                        }
                                        /*遍历投料单判断*/
                                        for (SysBomChild sysBomChild : oldBomList) {
                                            double should = 0;
                                            double actual = 0;
                                            if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                                if (sysBomChild.getMaterialId().equals("7.Y13A1A000001")
                                                        || sysBomChild.getMaterialId().equals("7.Y13A1A000002")
                                                        || sysBomChild.getMaterialId().equals("7.Y18A1A000001")
                                                        || sysBomChild.getMaterialId().equals("7.Y11A1A100120")
                                                        || sysBomChild.getMaterialId().equals("7.Y11A1A000349")) {
                                                    if (sysProductRecord.isHasWeight()) {
                                                        should = 0;
                                                        actual = sysProductRecord.getEndWeight1().doubleValue();
                                                    } else {
                                                        should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                                                        actual = sysBomChild.getHasGetNum();
                                                    }

                                                } else {
                                                    if (hasTwoMaterial) {
                                                        if (sysProductRecord.isTwoWeight()) {
                                                            should = 0;
                                                            actual = sysProductRecord.getEndWeight2().doubleValue();

                                                        } else {
                                                            should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                                                            actual = sysBomChild.getHasGetNum();
                                                        }
                                                    } else {
                                                        if (sysProductRecord.isHasWeight()) {
                                                            should = 0;
                                                            actual = sysProductRecord.getEndWeight1().doubleValue();
                                                        } else {
                                                            should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                                                            actual = sysBomChild.getHasGetNum();
                                                        }
                                                    }
//                                            should = 0;
//                                            try {
//                                                if(sysProductRecord.isHasWeight()){
//                                                    should = 0;
//                                                    actual = sysProductRecord.getEndWeight2().doubleValue();
//                                                }else{
//                                                    should=sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
//                                                    actual=sysBomChild.getHasGetNum();
//                                                }
//                                            } catch (Exception e) {
//                                                actual = 0;
//                                            }
                                                }
                                            } else {
                                                should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                                                actual = sysBomChild.getHasGetNum();
                                            }
                                            log.error("516应发：{}，已发：{}", should, actual);
                                            if (hasY > 0 && hasC == 1 && sysBomChild.getMaterialId().startsWith("7.Y")) {
                                                log.error("有次料，有原料");
                                                if (sysBomChildG.getMaterialId().equals(sysBomChild.getMaterialId())) {
                                                    YP = totalYS / totalS;
                                                    GP = totalGS / totalS;
                                                    if (sysProductRecord.isTwoWeight()) {
                                                        if (sysBomChild.getMaterialId().equals("7.Y13A1A000001")
                                                                || sysBomChild.getMaterialId().equals("7.Y13A1A000002")
                                                                || sysBomChild.getMaterialId().equals("7.Y18A1A000001")
                                                                || sysBomChild.getMaterialId().equals("7.Y11A1A100120")
                                                                || sysBomChild.getMaterialId().equals("7.Y11A1A000349")) {
                                                            log.error("2称1");
                                                            should = 0;
                                                            actual = sysProductRecord.getEndWeight1().doubleValue();
                                                        } else {
                                                            log.error("2称2");
                                                            should = 0;
                                                            actual = sysProductRecord.getEndWeight2().doubleValue();
                                                        }

                                                    } else if (sysProductRecord.isHasWeight()) {
                                                        actual = sysProductRecord.getEndWeight1().doubleValue();
                                                        should = 0;
                                                    } else {
                                                        should = sysBomChildG.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                                                        actual = sysBomChildG.getHasGetNum();
                                                    }

                                                    double resultNum = actual - should;
                                                    log.error("有次料的物料：{},应发：{},实发：{},退：{}", sysBomChildG.getMaterialName(), should, actual, resultNum);
                                                    if (resultNum > 0) {
                                                        /*退次*/
                                                        PickData pickData2 = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChildG, resultNum * GP);
                                                        KingdeeResult kingdeeResult2 = this.kingdeeUtils.addPick(pickData2);
                                                        if (kingdeeResult2.getStatusCode() == 200) {
                                                            saveMaterialRecord(oldWorkPlan, sysBomChildG, -resultNum * GP, pickData2, kingdeeResult2, false);
                                                        }
                                                        log.error("包括次料退次");
                                                        if (sysBomChild.isSame()) {
                                                            log.error("包括次料领次");
                                                            PickData pickData3 = this.kingdeeUtils.materialUntilGet(newWorkPlan, sysBomChild.getChildBomChild(), resultNum * GP);
                                                            KingdeeResult kingdeeResult3 = this.kingdeeUtils.addPick(pickData3);
                                                            if (kingdeeResult3.getStatusCode() == 200) {
                                                                saveMaterialRecord(newWorkPlan, sysBomChild.getChildBomChild(), resultNum * GP, pickData3, kingdeeResult3, true);
                                                            }
                                                        }
                                                    } else {
                                                        log.error("料号：{}，料名：{}无需退料", sysBomChildG.getMaterialId(), sysBomChildG.getMaterialName());
                                                        log.error("料号：{}，料名：{}无需退料", sysBomChildY.getMaterialId(), sysBomChildY.getMaterialName());
                                                    }
                                                } else if (
                                                        sysBomChildY.getMaterialId().equals(sysBomChild.getMaterialId())
                                                                && (!sysBomChildY.getMaterialId().equals("7.Y13A1A000001")
                                                                && !sysBomChildY.getMaterialId().equals("7.Y18A1A000001")
                                                                && !sysBomChildY.getMaterialId().equals("7.Y11A1A000349")
                                                                && !sysBomChildY.getMaterialId().equals("7.Y11A1A100120")
                                                                && !sysBomChildY.getMaterialId().equals("7.Y13A1A000002")
                                                        )) {
                                                    YP = totalYS / totalS;
                                                    GP = totalGS / totalS;
                                                    if (sysProductRecord.isTwoWeight()) {
                                                        actual = sysProductRecord.getEndWeight2().doubleValue();
                                                        should = 0;
                                                    } else if (sysProductRecord.isHasWeight()) {
                                                        actual = sysProductRecord.getEndWeight1().doubleValue();
                                                        should = 0;
                                                    } else {
                                                        should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                                                        actual = sysBomChild.getHasGetNum();
                                                    }
                                                    double resultNum = actual - should;
                                                    log.error("有软胶物料：{},应发：{},实发：{},退：{}", sysBomChild.getMaterialName(), should, actual, resultNum);

                                                    if (resultNum > 0) {
                                                        /*退原料*/
                                                        if (sysBomChildY.getMaterialId().startsWith("7.Y")) {
                                                            PickData pickData = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChildY, resultNum * YP);
                                                            KingdeeResult kingdeeResult = this.kingdeeUtils.addPick(pickData);
                                                            if (kingdeeResult.getStatusCode() == 200) {
                                                                saveMaterialRecord(oldWorkPlan, sysBomChildY, -resultNum * YP, pickData, kingdeeResult, false);
                                                            }
                                                        } else {
                                                            PickData pickData = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChild, resultNum);
                                                            KingdeeResult kingdeeResult = this.kingdeeUtils.addPick(pickData);
                                                            if (kingdeeResult.getStatusCode() == 200) {
                                                                saveMaterialRecord(oldWorkPlan, sysBomChild, -resultNum, pickData, kingdeeResult, false);
                                                            }
                                                        }
                                                        log.error("包括次料退原料");
                                                        if (sysBomChild.isSame()) {
                                                            log.error("包括次料领原料");
                                                            if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                                                PickData pickData1 = this.kingdeeUtils.materialUntilGet(newWorkPlan, sysBomChild.getChildBomChild(), resultNum * YP);
                                                                KingdeeResult kingdeeResult1 = this.kingdeeUtils.addPick(pickData1);
                                                                if (kingdeeResult1.getStatusCode() == 200) {
                                                                    saveMaterialRecord(newWorkPlan, sysBomChild.getChildBomChild(), resultNum * YP, pickData1, kingdeeResult1, true);
                                                                }
                                                            } else {
                                                                PickData pickData1 = this.kingdeeUtils.materialUntilGet(newWorkPlan, sysBomChild.getChildBomChild(), resultNum);
                                                                KingdeeResult kingdeeResult1 = this.kingdeeUtils.addPick(pickData1);
                                                                if (kingdeeResult1.getStatusCode() == 200) {
                                                                    saveMaterialRecord(newWorkPlan, sysBomChild.getChildBomChild(), resultNum, pickData1, kingdeeResult1, true);
                                                                }

                                                            }

                                                        }
                                                    } else {
                                                        log.error("料号：{}，料名：{}无需退料", sysBomChildG.getMaterialId(), sysBomChildG.getMaterialName());
                                                        log.error("料号：{}，料名：{}无需退料", sysBomChildY.getMaterialId(), sysBomChildY.getMaterialName());
                                                    }
                                                } else {
//                                            if(sysProductRecord.isHasWeight()){
//                                                actual=sysProductRecord.getEndWeight1().doubleValue();
//                                                should=0;
//                                            }else{
//                                                should=sysProductRecord.getTotalCount()*sysBomChild.getUnitNum().doubleValue();
//                                                actual=sysBomChild.getHasGetNum();
//                                            }
                                                    double resultNum = actual - should;
                                                    log.error("物料原料1：{},应发：{},实发：{},退：{}", sysBomChild.getMaterialName(), should, actual, resultNum);
                                                    if (resultNum > 0) {
                                                        log.error("不包括次料退");
                                                        PickData pickData = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChild, resultNum);
                                                        KingdeeResult kingdeeResult = this.kingdeeUtils.addPick(pickData);
                                                        if (kingdeeResult.getStatusCode() == 200) {
                                                            saveMaterialRecord(oldWorkPlan, sysBomChild, -resultNum, pickData, kingdeeResult, false);
                                                        }
                                                        if (sysBomChild.isSame()) {
                                                            log.error("不包括次料领");
                                                            PickData pickData1 = this.kingdeeUtils.materialUntilGet(newWorkPlan, sysBomChild.getChildBomChild(), resultNum);
                                                            KingdeeResult kingdeeResult1 = this.kingdeeUtils.addPick(pickData1);
                                                            if (kingdeeResult1.getStatusCode() == 200) {
                                                                saveMaterialRecord(newWorkPlan, sysBomChild.getChildBomChild(), resultNum, pickData1, kingdeeResult1, true);
                                                            }
                                                        }
                                                    } else {
                                                        log.error("料号2：{}，料名：{}无需退料", sysBomChild.getMaterialId(), sysBomChild.getMaterialName());
                                                    }
                                                }
                                            } else {
                                                log.error("DDDD:{}", sysBomChild);
                                                if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                                    if (sysProductRecord.isTwoWeight()) {
                                                        if (sysBomChild.getMaterialId().equals("7.Y13A1A000001")
                                                                || sysBomChild.getMaterialId().equals("7.Y13A1A000002")
                                                                || sysBomChild.getMaterialId().equals("7.Y18A1A000001")
                                                                || sysBomChild.getMaterialId().equals("7.Y11A1A100120")
                                                                || sysBomChild.getMaterialId().equals("7.Y11A1A000349")) {
                                                            log.error("2称1");
                                                            should = 0;
                                                            actual = sysProductRecord.getEndWeight1().doubleValue();
                                                        } else {
                                                            log.error("2称2");
                                                            should = 0;
                                                            actual = sysProductRecord.getEndWeight2().doubleValue();
                                                        }

                                                    } else if (sysProductRecord.isHasWeight()) {
                                                        log.error("1称");
                                                        should = 0;
                                                        actual = sysProductRecord.getEndWeight1().doubleValue();
                                                    } else {
                                                        log.error("0称");
                                                        should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                                                        actual = sysBomChild.getHasGetNum();
                                                    }
                                                } else {
                                                    should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                                                    actual = sysBomChild.getHasGetNum();
                                                }
                                                double resultNum = actual - should;
                                                log.error("物料1：{},应发1：{},实发1：{},退：{}", sysBomChild.getMaterialName(), should, actual, resultNum);
                                                if (resultNum > 0) {
                                                    log.error("不包括次料退");
                                                    PickData pickData = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChild, resultNum);
                                                    KingdeeResult kingdeeResult = this.kingdeeUtils.addPick(pickData);
                                                    if (kingdeeResult.getStatusCode() == 200) {
                                                        saveMaterialRecord(oldWorkPlan, sysBomChild, -resultNum, pickData, kingdeeResult, false);
                                                    }
                                                    if (sysBomChild.isSame()) {
                                                        log.error("不包括次料领");
                                                        if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                                            PickData pickData1 = this.kingdeeUtils.materialUntilGet(newWorkPlan, sysBomChild, resultNum);
                                                            KingdeeResult kingdeeResult1 = this.kingdeeUtils.addPick(pickData1);
                                                            if (kingdeeResult1.getStatusCode() == 200) {
                                                                saveMaterialRecord(newWorkPlan, sysBomChild, resultNum, pickData1, kingdeeResult1, true);
                                                            }
                                                        } else {
                                                            PickData pickData1 = this.kingdeeUtils.materialUntilGet(newWorkPlan, sysBomChild, resultNum);
                                                            KingdeeResult kingdeeResult1 = this.kingdeeUtils.addPick(pickData1);
                                                            if (kingdeeResult1.getStatusCode() == 200) {
                                                                saveMaterialRecord(newWorkPlan, sysBomChild, resultNum, pickData1, kingdeeResult1, true);
                                                            }
                                                        }

                                                    }
                                                } else {
                                                    log.error("料号：{}，料名：{}无需退料", sysBomChild.getMaterialId(), sysBomChild.getMaterialName());
                                                }
                                            }

                                        }

                                    }
                                } catch (Exception e) {
                                    log.error("Exception:{}", e.getMessage());
                                    sysProductRecord.setContinue(true);
                                    sysProductRecord.setNormal(true);
                                    sysProductRecord.setOver(true);
                                    sysProductRecord.setStart(true);
                                    this.sysProductRecordService.updateById(sysProductRecord);
                                }
                            } else {
                                sysProductRecord.setContinue(true);
                                sysProductRecord.setNormal(true);
                                sysProductRecord.setOver(true);
                                sysProductRecord.setStart(true);
                                this.sysProductRecordService.updateById(sysProductRecord);
                                return ResultTool.success();
                            }
                        }
                    }

                }
                else if (workPlanList.size() == 2) {
                    localDate = LocalDate.now().minusDays(1);
                    localDateTime = localDate.atTime(0, 0, 0);
                    queryWrapper = QueryWrapper.create();
//                    queryWrapper.where(SYS_WORK_PLAN.PRODUCT_STATUS.eq(1));
//                    queryWrapper.where(SYS_WORK_PLAN.MACHINE_NAME.eq(machineName));
//                    queryWrapper.where(SYS_WORK_PLAN.PLAN_START_TIME.eq(localDateTime));

                    queryWrapper.where(SYS_WORK_PLAN.WORK_PLAN_ID.eq(workPlanList.get(0).getWorkPlanId()).or(SYS_WORK_PLAN.WORK_PLAN_ID.eq(workPlanList.get(1).getWorkPlanId())));

                    queryWrapper.orderBy(SYS_WORK_PLAN.WORK_PLAN_ID, true);
                    queryWrapper.limit(2);
                    List<SysWorkPlan> oldWokPlanList = this.sysWorkPlanService.list(queryWrapper);
                    for (SysWorkPlan workPlan : oldWokPlanList) {
                        queryWrapper = QueryWrapper.create();
                        queryWrapper.where(SYS_BOM.PRODUCT_ICMO_ID.eq(workPlan.getInterId()));
                        queryWrapper.orderBy(SYS_BOM.ID, false);
                        queryWrapper.limit(1);
                        SysBom bom = this.sysBomService.getOne(queryWrapper);
                        if (bom != null) {
                            workPlan.setBom(bom);
                        }

                    }
                    log.error("OLD:{}", oldWokPlanList);
                    if (oldWokPlanList.size() == 2) {
                        SysWorkPlan oldWorkPlan1 = oldWokPlanList.get(0);
                        SysWorkPlan oldWorkPlan2 = oldWokPlanList.get(1);
                        SysWorkPlan newWorkPlan1 = workPlanList.get(0);
                        SysWorkPlan newWorkPlan2 = workPlanList.get(1);
                        if (oldWorkPlan1.isMoldSame() && oldWorkPlan2.isMoldSame() && newWorkPlan1.isMoldSame() && newWorkPlan2.isMoldSame()) {
                            List<SysBomChild> oldBomChildList1 = this.kingdeeUtils.getPPBOMDetail(oldWorkPlan1.getBom().getId());
                            List<SysBomChild> oldBomChildList2 = this.kingdeeUtils.getPPBOMDetail(oldWorkPlan2.getBom().getId());
                            List<SysBomChild> newBomChildList1 = this.kingdeeUtils.getPPBOMDetail(newWorkPlan1.getBom().getId());
                            List<SysBomChild> newBomChildList2 = this.kingdeeUtils.getPPBOMDetail(newWorkPlan2.getBom().getId());

                            double nTotal = 0;
                            double oTotal = 0;
                            double nY1 = 0;
                            double nY2 = 0;
                            double oY1 = 0;
                            double oY2 = 0;
                            for (SysBomChild sysBomChild : oldBomChildList1) {
                                if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                    oY1 += sysBomChild.getStandardNum().doubleValue();
                                    oTotal += sysBomChild.getStandardNum().doubleValue();
                                }

                            }
                            for (SysBomChild sysBomChild : oldBomChildList2) {
                                if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                    oY2 += sysBomChild.getStandardNum().doubleValue();
                                    oTotal += sysBomChild.getStandardNum().doubleValue();

                                }
                            }
                            for (SysBomChild sysBomChild : newBomChildList1) {
                                if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                    nY1 += sysBomChild.getStandardNum().doubleValue();
                                    nTotal += sysBomChild.getStandardNum().doubleValue();
                                }
                            }
                            for (SysBomChild sysBomChild : newBomChildList2) {
                                if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                    nY2 += sysBomChild.getStandardNum().doubleValue();
                                    nTotal += sysBomChild.getStandardNum().doubleValue();
                                }
                            }
                            DecimalFormat df = new DecimalFormat("#.##");
                            log.error("Old1:{},New1:{}", oY1, nY1);
                            log.error("Old2:{},New2:{}", oY2, nY2);
                            log.error("Old2:{},New2:{}", oTotal, nTotal);
                            log.error("TotalOld1:{},TotalNew1:{}", df.format(oY1 / oTotal), df.format(nY1 / nTotal));
                            log.error("TotalOld2:{},TotalNew2:{}", df.format(oY2 / oTotal), df.format(nY2 / nTotal));
                            double oldP1 = Double.parseDouble(df.format(oY1 / oTotal));
                            double oldP2 = Double.parseDouble(df.format(oY2 / oTotal));
                            double newP1 = Double.parseDouble(df.format(nY1 / nTotal));
                            double newP2 = Double.parseDouble(df.format(nY2 / nTotal));
                            if (oldP1 == newP1 && oldP2 == newP2) {
                                SysWorkPlan workPlan = sysProductRecord.getWorkPlan();
                                SysWorkPlan oldWorkPlan = null;
                                List<SysBomChild> oldBomList = new ArrayList<>();
                                List<SysBomChild> newBomList = new ArrayList<>();
                                double oP = 1;
                                double nP = 1;
                                if (workPlan.getProductId().equals(oldWorkPlan1.getProductId())) {

                                    oldWorkPlan = oldWorkPlan1;
                                    log.error("工单1:{}", oldWorkPlan);
                                    oP = oldP1;
                                    oldBomList = oldBomChildList1.stream().filter(item -> !item.getMaterialId().startsWith("9.")).collect(Collectors.toList());
                                    log.error("OldBomList:{}", JSONArray.toJSONString(oldBomList));
                                } else if (workPlan.getProductId().equals(oldWorkPlan2.getProductId())) {

                                    oldWorkPlan = oldWorkPlan2;
                                    log.error("工单2:{}", oldWorkPlan);
                                    oldBomList = oldBomChildList2.stream().filter(item -> !item.getMaterialId().startsWith("9.")).collect(Collectors.toList());
                                    oP = oldP2;
                                }
                                if (oldWorkPlan != null) {
                                    /*有工单则将当前生产工单关闭，切换到最近计划开始时间的工单*/

                                    sysProductRecord.setNormal(false);
                                    sysProductRecord.setOver(false);
                                    sysProductRecord.setContinue(false);
                                    sysProductRecord.setSummary(summary);
                                    sysProductRecord.setActualEndTime(new Date());
                                    sysProductRecord.setEntry(true);
                                    /*有电子称*/
                                    if (sysProductRecord.isHasWeight()) {
                                        queryWrapper = QueryWrapper.create();
                                        queryWrapper.where(SYS_MACHINE_PLC.MACHINE_NAME.eq(sysProductRecord.getMachineName()));
//                                                double weight=sysProductRecord.getEndWeight1().doubleValue();
                                        SysMachinePlc sysMachinePlc = this.sysMachinePlcService.getOne(queryWrapper);
                                        if (sysMachinePlc != null) {
                                            sysProductRecord = this.getWeightDataEnd(sysMachinePlc, sysProductRecord);

                                        } else {
                                            sysProductRecord.setTwoWeight(false);
                                            sysProductRecord.setHasWeight(false);
                                        }
                                    } else {
                                        sysProductRecord.setTwoWeight(false);
                                        sysProductRecord.setHasWeight(false);
                                    }
//                                    boolean result = true;
                                    /*更新当前生产记录状态*/
                                    sysProductRecord.setEndUserName("SYSTEM1");
                                    sysProductRecord.setEndUserId("SYSTEM1");
                                    boolean result = sysProductRecordService.updateById(sysProductRecord);
                                    if (result) {
                                        oldWorkPlan.setEnd(true);
                                        /*更新当前生产工单状态*/
                                        result = this.sysWorkPlanService.updateById(oldWorkPlan);
//                                        result = true;
                                        if (result) {
                                            SysWorkPlan newWorkPlan = null;
                                            if (workPlan.getProductId().equals(newWorkPlan1.getProductId())) {
                                                newWorkPlan = newWorkPlan1;
                                                nP = newP1;
                                                newBomList = newBomChildList1.stream().filter(item -> !item.getMaterialId().startsWith("9.")).collect(Collectors.toList());
                                                log.error("OldBomList:{}", JSONArray.toJSONString(newBomList));
                                            } else if (workPlan.getProductId().equals(newWorkPlan2.getProductId())) {
                                                newWorkPlan = newWorkPlan2;
                                                newBomList = newBomChildList2.stream().filter(item -> !item.getMaterialId().startsWith("9.")).collect(Collectors.toList());
                                                nP = newP2;
                                            }
                                            /*判断当前工单是否在生产*/
                                            /*如果在生产，则继续生产当前工单*/
                                            if (newWorkPlan != null) {
                                                log.error("OP百分比：{}", oP);
                                                SysProductRecord sysProductRecord1 = new SysProductRecord();
                                                Date productDate = new Date();
                                                String id = fromDateToString("yyyyMMddHHmm", productDate) + sysProductRecord.getMachineName() + newWorkPlan.getWorkPlanId();
                                                sysProductRecord1.setId(UUID.randomUUID().toString());
                                                sysProductRecord1.setProductDate(productDate);
                                                sysProductRecord1.setContinue(true);
                                                sysProductRecord1.setOver(false);
                                                sysProductRecord1.setStart(true);
                                                sysProductRecord1.setNormal(true);
                                                sysProductRecord1.setGoodNum(0);
                                                sysProductRecord1.setStart(true);
                                                sysProductRecord1.setNormal(true);
                                                sysProductRecord1.setEntry(false);
                                                sysProductRecord1.setActualStartTime(new Date());
                                                sysProductRecord1.setTotalCount(0);
                                                sysProductRecord1.setProductName(newWorkPlan.getProductName());
                                                sysProductRecord1.setShortName(newWorkPlan.getShortName());
                                                sysProductRecord1.setWorkPlanProductNum(newWorkPlan.getProductNum());
                                                sysProductRecord1.setWorkPlanId(newWorkPlan.getWorkPlanId());
                                                sysProductRecord1.setProductId(newWorkPlan.getProductId());
                                                sysProductRecord1.setAuto(true);
                                                sysProductRecord1.setMachineArea(sysProductRecord.getMachineArea());
                                                sysProductRecord1.setMachineName(sysProductRecord.getMachineName());
                                                LocalDateTime now = LocalDateTime.now();
                                                LocalDateTime localDate2 = LocalDateTime.of(now.getYear(), now.getMonthValue(), now.getDayOfMonth(), 20, 0, 0);
                                                LocalDateTime localDate1 = LocalDateTime.of(now.getYear(), now.getMonthValue(), now.getDayOfMonth(), 8, 0, 0);
                                                if (now.isAfter(localDate2) && now.isBefore(localDate1)) {
                                                    sysProductRecord1.setShift("夜班");
                                                } else {
                                                    sysProductRecord1.setShift("白班");
                                                }
                                                sysProductRecord1.setWorkPlanId(newWorkPlan.getWorkPlanId());
                                                sysProductRecord1.setActualStartTime(new Date());
                                                sysProductRecord1.setJobNo("SYSTEM1");
                                                sysProductRecord1.setUserName("SYSTEM1");
                                                sysProductRecord1.setHasWeight(sysProductRecord.getSysMachinePlc().isHasWeight());
                                                sysProductRecord1.setTwoWeight(sysProductRecord.getSysMachinePlc().isHasTwoWeight());
                                                if (sysProductRecord.isHasWeight()) {
                                                    sysProductRecord1.setStartWeight1(sysProductRecord.getEndWeight1().subtract(BigDecimal.valueOf(13).max(BigDecimal.valueOf(0))));
                                                } else {
                                                    sysProductRecord1.setStartWeight1(BigDecimal.valueOf(0));
                                                }
                                                if (sysProductRecord.isTwoWeight()) {
                                                    sysProductRecord1.setStartWeight2(sysProductRecord.getEndWeight2().subtract(BigDecimal.valueOf(13).max(BigDecimal.valueOf(0))));
                                                } else {
                                                    sysProductRecord1.setStartWeight2(BigDecimal.valueOf(0));
                                                }
                                                sysProductRecord1.setMoldSame(sysProductRecord.isMoldSame());
                                                sysProductRecord1.setExchangeType(sysProductRecord.getExchangeType());
                                                sysProductRecord1.setPaperBoxNumber(sysProductRecord.getPaperBoxNumber());
                                                sysProductRecord1.setExchangeType(newWorkPlan.getExchangeType());
                                                try {
                                                    result = this.sysProductRecordService.save(sysProductRecord1);
//                                                    result = true;
                                                    if (result) {


                                                        if (newBomList.size() > 0) {
                                                            List<String> materialIdList = new ArrayList<>();
                                                            newBomList.forEach(newItem -> {
                                                                materialIdList.add(newItem.getMaterialId().trim());
                                                            });
                                                            for (SysBomChild sysBomChild : oldBomList) {
                                                                if (materialIdList.contains(sysBomChild.getMaterialId().trim())) {
                                                                    sysBomChild.setSame(true);
                                                                    int index = materialIdList.indexOf(sysBomChild.getMaterialId().trim());
                                                                    sysBomChild.setChildBomChild(newBomList.get(index));
                                                                }
                                                            }

                                                        } else {
                                                            oldBomList.forEach(oldItem -> {
                                                                oldItem.setSame(false);
                                                            });
                                                        }

                                                        double totalYS = 0;//原料标准用量
                                                        double totalY = 0;//原料已领数量
                                                        double totalGS = 0;//改性标准用量
                                                        double totalG = 0;//改性已领数量
                                                        double totalS = 0;//总标准用量


                                                        double YP = 0;//
                                                        double GP = 0;//

                                                        SysBomChild sysBomChildY = new SysBomChild();
                                                        SysBomChild sysBomChildG = new SysBomChild();
                                                        int hasY = 0;
                                                        int hasC = 0;
                                                        oldBomList = oldBomList.stream().filter(item -> item.getAuxqtyPick().doubleValue() > 0).collect(Collectors.toList());
                                                        List<SysBomChild> sysBomChildList = oldBomList.stream().filter(item ->
                                                                item.getMaterialId().startsWith("7.Y")
                                                                        && (!item.getMaterialId().equals("7.Y11A1A000349")
                                                                        && !item.getMaterialId().equals("7.Y18A1A000001")
                                                                        && !item.getMaterialId().equals("7.Y13A1A000002")
                                                                        && !item.getMaterialId().equals("7.Y11A1A100120")
                                                                )).collect(Collectors.toList());                                                        /*判断是否有改性料并添加表四*/
                                                        for (SysBomChild sysBomChild : sysBomChildList) {
                                                            String materialName = sysBomChild.getMaterialName();
                                                            if ((materialName.contains("改性") || materialName.contains("抽粒") || materialName.contains("次料")) && sysBomChild.getAuxqtyPick().doubleValue() > 0) {
                                                                totalG += sysBomChild.getHasGetNum();
                                                                totalGS = sysBomChild.getStandardNum().doubleValue();
                                                                sysBomChild.setG(true);
                                                                sysBomChildG = sysBomChild;
                                                                hasC++;
                                                            } else if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                                                hasY++;
                                                                sysBomChildY = sysBomChild;
                                                                totalY += sysBomChild.getHasGetNum();
                                                                totalYS = sysBomChild.getStandardNum().doubleValue();
                                                            }
                                                            totalS += sysBomChild.getStandardNum().doubleValue();
                                                        }
                                                        /*遍历投料单判断*/
                                                        for (SysBomChild sysBomChild : oldBomList) {
                                                            double should = 0;
                                                            double actual = 0;
                                                            if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                                                if (sysBomChild.getMaterialId().equals("7.Y13A1A000001")
                                                                        || sysBomChild.getMaterialId().equals("7.Y13A1A000002")
                                                                        || sysBomChild.getMaterialId().equals("7.Y18A1A000001")
                                                                        || sysBomChild.getMaterialId().equals("7.Y11A1A100120")
                                                                        || sysBomChild.getMaterialId().equals("7.Y11A1A000349")) {
                                                                    if (sysProductRecord.isHasWeight()) {
                                                                        should = 0;
                                                                        actual = sysProductRecord.getEndWeight1().doubleValue();
                                                                        actual = actual * oP;
                                                                    } else {
                                                                        should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount() * oP;
                                                                        actual = sysBomChild.getHasGetNum() * oP;
                                                                    }

                                                                } else {
//
                                                                }
                                                            } else {
                                                                should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                                                                actual = sysBomChild.getHasGetNum();
                                                            }
                                                            if (hasY > 0 && hasC == 1 && sysBomChild.getMaterialId().startsWith("7.Y")) {
                                                                log.error("有次料，有原料");
                                                                if (sysBomChildG.getMaterialId().equals(sysBomChild.getMaterialId())) {
                                                                    YP = totalYS / totalS;
                                                                    GP = totalGS / totalS;
                                                                    if (sysProductRecord.isTwoWeight()) {
                                                                        if (sysBomChild.getMaterialId().equals("7.Y13A1A000001")
                                                                                || sysBomChild.getMaterialId().equals("7.Y13A1A000002")
                                                                                || sysBomChild.getMaterialId().equals("7.Y18A1A000001")
                                                                                || sysBomChild.getMaterialId().equals("7.Y11A1A100120")
                                                                                || sysBomChild.getMaterialId().equals("7.Y11A1A000349")) {
                                                                            log.error("2称1");
                                                                            should = 0;
                                                                            actual = sysProductRecord.getEndWeight1().doubleValue();
                                                                        } else {
                                                                            log.error("2称2");
                                                                            should = 0;
                                                                            actual = sysProductRecord.getEndWeight2().doubleValue();
                                                                        }

                                                                    } else if (sysProductRecord.isHasWeight()) {
                                                                        actual = sysProductRecord.getEndWeight1().doubleValue();
                                                                        actual = actual * oP;
                                                                        should = 0;
                                                                    } else {
                                                                        should = sysBomChildG.getUnitNum().doubleValue() * sysProductRecord.getTotalCount() * oP;
                                                                        actual = sysBomChildG.getHasGetNum() * oP;
                                                                    }
                                                                    double resultNum = actual - should;
                                                                    log.error("有次料的物料：{},应发：{},实发：{},退：{}", sysBomChildG.getMaterialName(), should, actual, resultNum);
                                                                    if (resultNum > 0) {
                                                                        /*退次*/
                                                                        PickData pickData2 = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChildG, resultNum * GP);
                                                                        KingdeeResult kingdeeResult2 = this.kingdeeUtils.addPick(pickData2);
                                                                        if (kingdeeResult2.getStatusCode() == 200) {
                                                                            saveMaterialRecord(oldWorkPlan, sysBomChildG, -resultNum * GP, pickData2, kingdeeResult2, false);
                                                                        }
                                                                        log.error("包括次料退次");
                                                                        if (sysBomChild.isSame()) {
                                                                            log.error("包括次料领次");
                                                                            PickData pickData3 = this.kingdeeUtils.materialUntilGet(newWorkPlan, sysBomChild.getChildBomChild(), resultNum * GP);
                                                                            KingdeeResult kingdeeResult3 = this.kingdeeUtils.addPick(pickData3);
                                                                            if (kingdeeResult3.getStatusCode() == 200) {
                                                                                saveMaterialRecord(newWorkPlan, sysBomChild.getChildBomChild(), resultNum * GP, pickData3, kingdeeResult3, true);
                                                                            }
                                                                        }
                                                                    } else {
                                                                        log.error("料号：{}，料名：{}无需退料", sysBomChildG.getMaterialId(), sysBomChildG.getMaterialName());
                                                                        log.error("料号：{}，料名：{}无需退料", sysBomChildY.getMaterialId(), sysBomChildY.getMaterialName());
                                                                    }
                                                                } else if (
                                                                        sysBomChildY.getMaterialId().equals(sysBomChild.getMaterialId())
                                                                                && (!sysBomChildY.getMaterialId().equals("7.Y13A1A000001")
                                                                                && !sysBomChildY.getMaterialId().equals("7.Y11A1A000349")
                                                                                && !sysBomChildY.getMaterialId().equals("7.Y18A1A000001")
                                                                                && !sysBomChildY.getMaterialId().equals("7.Y11A1A100120")
                                                                                && !sysBomChildY.getMaterialId().equals("7.Y13A1A000002")
                                                                        )) {
                                                                    YP = totalYS / totalS;
                                                                    GP = totalGS / totalS;
                                                                    if (sysProductRecord.isTwoWeight()) {
                                                                        if (sysBomChild.getMaterialId().equals("7.Y13A1A000001")
                                                                                || sysBomChild.getMaterialId().equals("7.Y13A1A000002")
                                                                                || sysBomChild.getMaterialId().equals("7.Y18A1A000001")
                                                                                || sysBomChild.getMaterialId().equals("7.Y11A1A100120")
                                                                                || sysBomChild.getMaterialId().equals("7.Y11A1A000349")) {
                                                                            log.error("2称1");
                                                                            should = 0;
                                                                            actual = sysProductRecord.getEndWeight1().doubleValue();
                                                                        } else {
                                                                            log.error("2称2");
                                                                            should = 0;
                                                                            actual = sysProductRecord.getEndWeight2().doubleValue();
                                                                        }

                                                                    } else if (sysProductRecord.isHasWeight()) {
                                                                        actual = sysProductRecord.getEndWeight1().doubleValue();
                                                                        actual = actual * oP;
                                                                        should = 0;
                                                                    } else {
                                                                        should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount() * oP;
                                                                        actual = sysBomChild.getHasGetNum() * oP;
                                                                    }
                                                                    double resultNum = actual - should;
                                                                    log.error("有软胶物料：{},应发：{},实发：{},退：{}", sysBomChild.getMaterialName(), should, actual, resultNum);
                                                                    if (resultNum > 0) {
                                                                        /*退原料*/
                                                                        if (sysBomChildY.getMaterialId().startsWith("7.Y")) {
                                                                            PickData pickData = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChildY, resultNum * YP);
                                                                            KingdeeResult kingdeeResult = this.kingdeeUtils.addPick(pickData);
                                                                            if (kingdeeResult.getStatusCode() == 200) {
                                                                                saveMaterialRecord(oldWorkPlan, sysBomChildY, -resultNum * YP, pickData, kingdeeResult, false);
                                                                            }
                                                                        } else {
                                                                            PickData pickData = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChild, resultNum);
                                                                            KingdeeResult kingdeeResult = this.kingdeeUtils.addPick(pickData);
                                                                            if (kingdeeResult.getStatusCode() == 200) {
                                                                                saveMaterialRecord(oldWorkPlan, sysBomChild, -resultNum, pickData, kingdeeResult, false);
                                                                            }
                                                                        }
                                                                        log.error("包括次料退原料");
                                                                        if (sysBomChild.isSame()) {
                                                                            log.error("包括次料领原料");
                                                                            if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                                                                PickData pickData1 = this.kingdeeUtils.materialUntilGet(newWorkPlan, sysBomChild.getChildBomChild(), resultNum * YP);
                                                                                KingdeeResult kingdeeResult1 = this.kingdeeUtils.addPick(pickData1);
                                                                                if (kingdeeResult1.getStatusCode() == 200) {
                                                                                    saveMaterialRecord(newWorkPlan, sysBomChild.getChildBomChild(), resultNum * YP, pickData1, kingdeeResult1, true);
                                                                                }
                                                                            } else {
                                                                                PickData pickData1 = this.kingdeeUtils.materialUntilGet(newWorkPlan, sysBomChild.getChildBomChild(), resultNum);
                                                                                KingdeeResult kingdeeResult1 = this.kingdeeUtils.addPick(pickData1);
                                                                                if (kingdeeResult1.getStatusCode() == 200) {
                                                                                    saveMaterialRecord(newWorkPlan, sysBomChild.getChildBomChild(), resultNum, pickData1, kingdeeResult1, true);
                                                                                }
                                                                            }

                                                                        }
                                                                    } else {
                                                                        log.error("料号：{}，料名：{}无需退料", sysBomChildG.getMaterialId(), sysBomChildG.getMaterialName());
                                                                        log.error("料号：{}，料名：{}无需退料", sysBomChildY.getMaterialId(), sysBomChildY.getMaterialName());
                                                                    }
                                                                } else {
                                                                    double resultNum = actual - should;
                                                                    log.error("物料原料1：{},应发：{},实发：{},退：{}", sysBomChild.getMaterialName(), should, actual, resultNum);
                                                                    if (resultNum > 0) {
                                                                        log.error("不包括次料退");
                                                                        PickData pickData = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChild, resultNum);
                                                                        KingdeeResult kingdeeResult = this.kingdeeUtils.addPick(pickData);
                                                                        if (kingdeeResult.getStatusCode() == 200) {
                                                                            saveMaterialRecord(oldWorkPlan, sysBomChild, -resultNum, pickData, kingdeeResult, false);
                                                                        }
                                                                        if (sysBomChild.isSame()) {
                                                                            log.error("不包括次料领");
                                                                            PickData pickData1 = this.kingdeeUtils.materialUntilGet(newWorkPlan, sysBomChild.getChildBomChild(), resultNum);
                                                                            KingdeeResult kingdeeResult1 = this.kingdeeUtils.addPick(pickData1);
                                                                            if (kingdeeResult1.getStatusCode() == 200) {
                                                                                saveMaterialRecord(newWorkPlan, sysBomChild.getChildBomChild(), resultNum, pickData1, kingdeeResult1, true);
                                                                            }
                                                                        }
                                                                    } else {
                                                                        log.error("料号2：{}，料名：{}无需退料", sysBomChild.getMaterialId(), sysBomChild.getMaterialName());
                                                                    }
                                                                }
                                                            } else {
                                                                log.error("DDDD:{}", sysBomChild);
                                                                if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                                                    log.error("D:原料");
                                                                    if (sysProductRecord.isTwoWeight()) {
                                                                        if (sysBomChild.getMaterialId().equals("7.Y13A1A000001")
                                                                                || sysBomChild.getMaterialId().equals("7.Y13A1A000002")
                                                                                || sysBomChild.getMaterialId().equals("7.Y18A1A000001")
                                                                                || sysBomChild.getMaterialId().equals("7.Y11A1A100120")
                                                                                || sysBomChild.getMaterialId().equals("7.Y11A1A000349")) {
                                                                            log.error("2称1");
                                                                            should = 0;
                                                                            actual = sysProductRecord.getEndWeight1().doubleValue();
                                                                        } else {
                                                                            log.error("2称2");
                                                                            should = 0;
                                                                            actual = sysProductRecord.getEndWeight2().doubleValue();
                                                                        }

                                                                    } else if (sysProductRecord.isHasWeight()) {
                                                                        log.error("D:有");

                                                                        should = 0;
                                                                        actual = sysProductRecord.getEndWeight1().doubleValue();
                                                                        actual = actual * oP;
                                                                    } else {
                                                                        log.error("D:没有");
                                                                        should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount() * oP;
                                                                        actual = sysBomChild.getHasGetNum() * oP;
                                                                    }
                                                                } else {
                                                                    log.error("D:没有1");
                                                                    should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                                                                    actual = sysBomChild.getHasGetNum();
                                                                }
                                                                double resultNum = actual - should;
                                                                log.error("物料1：{},应发1：{},实发1：{},退：{}", sysBomChild.getMaterialName(), should, actual, resultNum);
                                                                if (resultNum > 0) {
                                                                    log.error("不包括次料退");
                                                                    PickData pickData = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChild, resultNum);
                                                                    KingdeeResult kingdeeResult = this.kingdeeUtils.addPick(pickData);
                                                                    if (kingdeeResult.getStatusCode() == 200) {
                                                                        saveMaterialRecord(oldWorkPlan, sysBomChild, -resultNum, pickData, kingdeeResult, false);
                                                                    }
                                                                    if (sysBomChild.isSame()) {
                                                                        log.error("不包括次料领");
                                                                        if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                                                            PickData pickData1 = this.kingdeeUtils.materialUntilGet(newWorkPlan, sysBomChild, resultNum);
                                                                            KingdeeResult kingdeeResult1 = this.kingdeeUtils.addPick(pickData1);
                                                                            if (kingdeeResult1.getStatusCode() == 200) {
                                                                                saveMaterialRecord(newWorkPlan, sysBomChild, resultNum, pickData1, kingdeeResult1, true);
                                                                            }
                                                                        } else {
                                                                            PickData pickData1 = this.kingdeeUtils.materialUntilGet(newWorkPlan, sysBomChild, resultNum);
                                                                            KingdeeResult kingdeeResult1 = this.kingdeeUtils.addPick(pickData1);
                                                                            if (kingdeeResult1.getStatusCode() == 200) {
                                                                                saveMaterialRecord(newWorkPlan, sysBomChild, resultNum, pickData1, kingdeeResult1, true);
                                                                            }
                                                                        }

                                                                    }
                                                                } else {
                                                                    log.error("料号：{}，料名：{}无需退料", sysBomChild.getMaterialId(), sysBomChild.getMaterialName());
                                                                }
                                                            }

                                                        }

                                                        return ResultTool.success();
                                                    }
                                                } catch (Exception e) {
                                                    log.error("Exception:{}", e.getMessage());
                                                    sysProductRecord.setContinue(true);
                                                    sysProductRecord.setNormal(true);
                                                    sysProductRecord.setOver(true);
                                                    sysProductRecord.setStart(true);
                                                    this.sysProductRecordService.updateById(sysProductRecord);
                                                }
                                            } else {
                                                sysProductRecord.setContinue(true);
                                                sysProductRecord.setNormal(true);
                                                sysProductRecord.setOver(true);
                                                sysProductRecord.setStart(true);
                                                this.sysProductRecordService.updateById(sysProductRecord);
                                                return ResultTool.fail();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }


                }
                else if (workPlanList.size() == 3) {
                    localDate = LocalDate.now().minusDays(1);
                    localDateTime = localDate.atTime(0, 0, 0);
                    queryWrapper = QueryWrapper.create();
//                    queryWrapper.where(SYS_WORK_PLAN.PRODUCT_STATUS.eq(1));
//                    queryWrapper.where(SYS_WORK_PLAN.MACHINE_NAME.eq(machineName));
//                    queryWrapper.where(SYS_WORK_PLAN.PLAN_START_TIME.eq(localDateTime));

                    queryWrapper.where(SYS_WORK_PLAN.WORK_PLAN_ID.eq(workPlanList.get(0).getWorkPlanId()).or(SYS_WORK_PLAN.WORK_PLAN_ID.eq(workPlanList.get(1).getWorkPlanId())));

                    queryWrapper.orderBy(SYS_WORK_PLAN.WORK_PLAN_ID, true);
                    queryWrapper.limit(3);
                    List<SysWorkPlan> oldWokPlanList = this.sysWorkPlanService.list(queryWrapper);
                    for (SysWorkPlan workPlan : oldWokPlanList) {
                        queryWrapper = QueryWrapper.create();
                        queryWrapper.where(SYS_BOM.PRODUCT_ICMO_ID.eq(workPlan.getInterId()));
                        queryWrapper.orderBy(SYS_BOM.ID, false);
                        queryWrapper.limit(1);
                        SysBom bom = this.sysBomService.getOne(queryWrapper);
                        if (bom != null) {
                            workPlan.setBom(bom);
                        }

                    }
                    log.error("OLD:{}", oldWokPlanList);
                    if (oldWokPlanList.size() == 3) {
                        SysWorkPlan oldWorkPlan1 = oldWokPlanList.get(0);
                        SysWorkPlan oldWorkPlan2 = oldWokPlanList.get(1);
                        SysWorkPlan oldWorkPlan3 = oldWokPlanList.get(2);
                        SysWorkPlan newWorkPlan1 = workPlanList.get(0);
                        SysWorkPlan newWorkPlan2 = workPlanList.get(1);
                        SysWorkPlan newWorkPlan3 = workPlanList.get(2);

                        if (oldWorkPlan1.isMoldSame() && oldWorkPlan2.isMoldSame() && newWorkPlan1.isMoldSame() && newWorkPlan2.isMoldSame()&&oldWorkPlan3.isMoldSame()&&newWorkPlan3.isMoldSame()) {
                            List<SysBomChild> oldBomChildList1 = this.kingdeeUtils.getPPBOMDetail(oldWorkPlan1.getBom().getId());
                            List<SysBomChild> oldBomChildList2 = this.kingdeeUtils.getPPBOMDetail(oldWorkPlan2.getBom().getId());
                            List<SysBomChild> oldBomChildList3 = this.kingdeeUtils.getPPBOMDetail(oldWorkPlan3.getBom().getId());
                            List<SysBomChild> newBomChildList1 = this.kingdeeUtils.getPPBOMDetail(newWorkPlan1.getBom().getId());
                            List<SysBomChild> newBomChildList2 = this.kingdeeUtils.getPPBOMDetail(newWorkPlan2.getBom().getId());
                            List<SysBomChild> newBomChildList3 = this.kingdeeUtils.getPPBOMDetail(newWorkPlan3.getBom().getId());

                            double nTotal = 0;
                            double oTotal = 0;
                            double nY1 = 0;
                            double nY2 = 0;
                            double nY3 = 0;
                            double oY1 = 0;
                            double oY2 = 0;
                            double oY3 = 0;
                            for (SysBomChild sysBomChild : oldBomChildList1) {
                                if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                    oY1 += sysBomChild.getStandardNum().doubleValue();
                                    oTotal += sysBomChild.getStandardNum().doubleValue();
                                }

                            }
                            for (SysBomChild sysBomChild : oldBomChildList2) {
                                if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                    oY2 += sysBomChild.getStandardNum().doubleValue();
                                    oTotal += sysBomChild.getStandardNum().doubleValue();

                                }
                            }
                            for (SysBomChild sysBomChild : oldBomChildList3) {
                                if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                    oY3 += sysBomChild.getStandardNum().doubleValue();
                                    oTotal += sysBomChild.getStandardNum().doubleValue();

                                }
                            }
                            for (SysBomChild sysBomChild : newBomChildList1) {
                                if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                    nY1 += sysBomChild.getStandardNum().doubleValue();
                                    nTotal += sysBomChild.getStandardNum().doubleValue();
                                }
                            }
                            for (SysBomChild sysBomChild : newBomChildList2) {
                                if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                    nY2 += sysBomChild.getStandardNum().doubleValue();
                                    nTotal += sysBomChild.getStandardNum().doubleValue();
                                }
                            }

                            for (SysBomChild sysBomChild : newBomChildList3) {
                                if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                    nY3 += sysBomChild.getStandardNum().doubleValue();
                                    nTotal += sysBomChild.getStandardNum().doubleValue();
                                }
                            }
                            DecimalFormat df = new DecimalFormat("#.##");
                            log.error("Old1:{},New1:{}", oY1, nY1);
                            log.error("Old2:{},New2:{}", oY2, nY2);
                            log.error("Old2:{},New2:{}", oTotal, nTotal);
                            log.error("TotalOld1:{},TotalNew1:{}", df.format(oY1 / oTotal), df.format(nY1 / nTotal));
                            log.error("TotalOld2:{},TotalNew2:{}", df.format(oY2 / oTotal), df.format(nY2 / nTotal));
                            double oldP1 = Double.parseDouble(df.format(oY1 / oTotal));
                            double oldP2 = Double.parseDouble(df.format(oY2 / oTotal));
                            double oldP3 = Double.parseDouble(df.format(oY3 / oTotal));
                            double newP1 = Double.parseDouble(df.format(nY1 / nTotal));
                            double newP2 = Double.parseDouble(df.format(nY2 / nTotal));
                            double newP3 = Double.parseDouble(df.format(nY3 / nTotal));
                            if (oldP1 == newP1 && oldP2 == newP2&&oldP3==newP3) {
                                SysWorkPlan workPlan = sysProductRecord.getWorkPlan();
                                SysWorkPlan oldWorkPlan = null;
                                List<SysBomChild> oldBomList = new ArrayList<>();
                                List<SysBomChild> newBomList = new ArrayList<>();
                                double oP = 1;
                                double nP = 1;
                                if (workPlan.getProductId().equals(oldWorkPlan1.getProductId())) {

                                    oldWorkPlan = oldWorkPlan1;
                                    log.error("工单1:{}", oldWorkPlan);
                                    oP = oldP1;
                                    oldBomList = oldBomChildList1.stream().filter(item -> !item.getMaterialId().startsWith("9.")).collect(Collectors.toList());
                                    log.error("OldBomList:{}", JSONArray.toJSONString(oldBomList));
                                } else if (workPlan.getProductId().equals(oldWorkPlan2.getProductId())) {

                                    oldWorkPlan = oldWorkPlan2;
                                    log.error("工单2:{}", oldWorkPlan);
                                    oldBomList = oldBomChildList2.stream().filter(item -> !item.getMaterialId().startsWith("9.")).collect(Collectors.toList());
                                    oP = oldP2;
                                }else if (workPlan.getProductId().equals(oldWorkPlan3.getProductId())) {

                                    oldWorkPlan = oldWorkPlan3;
                                    log.error("工单2:{}", oldWorkPlan);
                                    oldBomList = oldBomChildList3.stream().filter(item -> !item.getMaterialId().startsWith("9.")).collect(Collectors.toList());
                                    oP = oldP3;
                                }
                                if (oldWorkPlan != null) {
                                    /*有工单则将当前生产工单关闭，切换到最近计划开始时间的工单*/

                                    sysProductRecord.setNormal(false);
                                    sysProductRecord.setOver(false);
                                    sysProductRecord.setContinue(false);
                                    sysProductRecord.setSummary(summary);
                                    sysProductRecord.setActualEndTime(new Date());
                                    sysProductRecord.setEntry(true);
                                    /*有电子称*/
                                    if (sysProductRecord.isHasWeight()) {
                                        queryWrapper = QueryWrapper.create();
                                        queryWrapper.where(SYS_MACHINE_PLC.MACHINE_NAME.eq(sysProductRecord.getMachineName()));
//                                                double weight=sysProductRecord.getEndWeight1().doubleValue();
                                        SysMachinePlc sysMachinePlc = this.sysMachinePlcService.getOne(queryWrapper);
                                        if (sysMachinePlc != null) {
                                            sysProductRecord = this.getWeightDataEnd(sysMachinePlc, sysProductRecord);

                                        } else {
                                            sysProductRecord.setTwoWeight(false);
                                            sysProductRecord.setHasWeight(false);
                                        }
                                    } else {
                                        sysProductRecord.setTwoWeight(false);
                                        sysProductRecord.setHasWeight(false);
                                    }
//                                    boolean result = true;
                                    /*更新当前生产记录状态*/
                                    sysProductRecord.setEndUserName("SYSTEM1");
                                    sysProductRecord.setEndUserId("SYSTEM1");
                                    boolean result = sysProductRecordService.updateById(sysProductRecord);
                                    if (result) {
                                        oldWorkPlan.setEnd(true);
                                        /*更新当前生产工单状态*/
                                        result = this.sysWorkPlanService.updateById(oldWorkPlan);
//                                        result = true;
                                        if (result) {
                                            SysWorkPlan newWorkPlan = null;
                                            if (workPlan.getProductId().equals(newWorkPlan1.getProductId())) {
                                                newWorkPlan = newWorkPlan1;
                                                nP = newP1;
                                                newBomList = newBomChildList1.stream().filter(item -> !item.getMaterialId().startsWith("9.")).collect(Collectors.toList());
                                                log.error("OldBomList:{}", JSONArray.toJSONString(newBomList));
                                            } else if (workPlan.getProductId().equals(newWorkPlan2.getProductId())) {
                                                newWorkPlan = newWorkPlan2;
                                                newBomList = newBomChildList2.stream().filter(item -> !item.getMaterialId().startsWith("9.")).collect(Collectors.toList());
                                                nP = newP2;
                                            } else if (workPlan.getProductId().equals(newWorkPlan3.getProductId())) {
                                                newWorkPlan = newWorkPlan3;
                                                newBomList = newBomChildList3.stream().filter(item -> !item.getMaterialId().startsWith("9.")).collect(Collectors.toList());
                                                nP = newP3;
                                            }
                                            /*判断当前工单是否在生产*/
                                            /*如果在生产，则继续生产当前工单*/
                                            if (newWorkPlan != null) {
                                                log.error("OP百分比：{}", oP);
                                                SysProductRecord sysProductRecord1 = new SysProductRecord();
                                                Date productDate = new Date();
                                                String id = fromDateToString("yyyyMMddHHmm", productDate) + sysProductRecord.getMachineName() + newWorkPlan.getWorkPlanId();
                                                sysProductRecord1.setId(UUID.randomUUID().toString());
                                                sysProductRecord1.setProductDate(productDate);
                                                sysProductRecord1.setContinue(true);
                                                sysProductRecord1.setOver(false);
                                                sysProductRecord1.setStart(true);
                                                sysProductRecord1.setNormal(true);
                                                sysProductRecord1.setGoodNum(0);
                                                sysProductRecord1.setStart(true);
                                                sysProductRecord1.setNormal(true);
                                                sysProductRecord1.setEntry(false);
                                                sysProductRecord1.setActualStartTime(new Date());
                                                sysProductRecord1.setTotalCount(0);
                                                sysProductRecord1.setProductName(newWorkPlan.getProductName());
                                                sysProductRecord1.setShortName(newWorkPlan.getShortName());
                                                sysProductRecord1.setWorkPlanProductNum(newWorkPlan.getProductNum());
                                                sysProductRecord1.setWorkPlanId(newWorkPlan.getWorkPlanId());
                                                sysProductRecord1.setProductId(newWorkPlan.getProductId());
                                                sysProductRecord1.setAuto(true);
                                                sysProductRecord1.setMachineArea(sysProductRecord.getMachineArea());
                                                sysProductRecord1.setMachineName(sysProductRecord.getMachineName());
                                                LocalDateTime now = LocalDateTime.now();
                                                LocalDateTime localDate2 = LocalDateTime.of(now.getYear(), now.getMonthValue(), now.getDayOfMonth(), 20, 0, 0);
                                                LocalDateTime localDate1 = LocalDateTime.of(now.getYear(), now.getMonthValue(), now.getDayOfMonth(), 8, 0, 0);
                                                if (now.isAfter(localDate2) && now.isBefore(localDate1)) {
                                                    sysProductRecord1.setShift("夜班");
                                                } else {
                                                    sysProductRecord1.setShift("白班");
                                                }
                                                sysProductRecord1.setWorkPlanId(newWorkPlan.getWorkPlanId());
                                                sysProductRecord1.setActualStartTime(new Date());
                                                sysProductRecord1.setJobNo("SYSTEM1");
                                                sysProductRecord1.setUserName("SYSTEM1");
                                                sysProductRecord1.setHasWeight(sysProductRecord.getSysMachinePlc().isHasWeight());
                                                sysProductRecord1.setTwoWeight(sysProductRecord.getSysMachinePlc().isHasTwoWeight());
                                                if (sysProductRecord.isHasWeight()) {
                                                    sysProductRecord1.setStartWeight1(sysProductRecord.getEndWeight1().subtract(BigDecimal.valueOf(13).max(BigDecimal.valueOf(0))));
                                                } else {
                                                    sysProductRecord1.setStartWeight1(BigDecimal.valueOf(0));
                                                }
                                                if (sysProductRecord.isTwoWeight()) {
                                                    sysProductRecord1.setStartWeight2(sysProductRecord.getEndWeight2().subtract(BigDecimal.valueOf(13).max(BigDecimal.valueOf(0))));
                                                } else {
                                                    sysProductRecord1.setStartWeight2(BigDecimal.valueOf(0));
                                                }
                                                sysProductRecord1.setMoldSame(sysProductRecord.isMoldSame());
                                                sysProductRecord1.setExchangeType(sysProductRecord.getExchangeType());
                                                sysProductRecord1.setPaperBoxNumber(sysProductRecord.getPaperBoxNumber());
                                                sysProductRecord1.setExchangeType(newWorkPlan.getExchangeType());
                                                try {
                                                    result = this.sysProductRecordService.save(sysProductRecord1);
//                                                    result = true;
                                                    if (result) {


                                                        if (newBomList.size() > 0) {
                                                            List<String> materialIdList = new ArrayList<>();
                                                            newBomList.forEach(newItem -> {
                                                                materialIdList.add(newItem.getMaterialId().trim());
                                                            });
                                                            for (SysBomChild sysBomChild : oldBomList) {
                                                                if (materialIdList.contains(sysBomChild.getMaterialId().trim())) {
                                                                    sysBomChild.setSame(true);
                                                                    int index = materialIdList.indexOf(sysBomChild.getMaterialId().trim());
                                                                    sysBomChild.setChildBomChild(newBomList.get(index));
                                                                }
                                                            }

                                                        } else {
                                                            oldBomList.forEach(oldItem -> {
                                                                oldItem.setSame(false);
                                                            });
                                                        }

                                                        double totalYS = 0;//原料标准用量
                                                        double totalY = 0;//原料已领数量
                                                        double totalGS = 0;//改性标准用量
                                                        double totalG = 0;//改性已领数量
                                                        double totalS = 0;//总标准用量


                                                        double YP = 0;//
                                                        double GP = 0;//

                                                        SysBomChild sysBomChildY = new SysBomChild();
                                                        SysBomChild sysBomChildG = new SysBomChild();
                                                        int hasY = 0;
                                                        int hasC = 0;
                                                        oldBomList = oldBomList.stream().filter(item -> item.getAuxqtyPick().doubleValue() > 0).collect(Collectors.toList());
                                                        List<SysBomChild> sysBomChildList = oldBomList.stream().filter(item ->
                                                                item.getMaterialId().startsWith("7.Y")
                                                                        && (!item.getMaterialId().equals("7.Y11A1A000349")
                                                                        && !item.getMaterialId().equals("7.Y18A1A000001")
                                                                        && !item.getMaterialId().equals("7.Y13A1A000002")
                                                                        && !item.getMaterialId().equals("7.Y11A1A100120")
                                                                )).collect(Collectors.toList());                                                        /*判断是否有改性料并添加表四*/
                                                        for (SysBomChild sysBomChild : sysBomChildList) {
                                                            String materialName = sysBomChild.getMaterialName();
                                                            if ((materialName.contains("改性") || materialName.contains("抽粒") || materialName.contains("次料")) && sysBomChild.getAuxqtyPick().doubleValue() > 0) {
                                                                totalG += sysBomChild.getHasGetNum();
                                                                totalGS = sysBomChild.getStandardNum().doubleValue();
                                                                sysBomChild.setG(true);
                                                                sysBomChildG = sysBomChild;
                                                                hasC++;
                                                            } else if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                                                hasY++;
                                                                sysBomChildY = sysBomChild;
                                                                totalY += sysBomChild.getHasGetNum();
                                                                totalYS = sysBomChild.getStandardNum().doubleValue();
                                                            }
                                                            totalS += sysBomChild.getStandardNum().doubleValue();
                                                        }
                                                        /*遍历投料单判断*/
                                                        for (SysBomChild sysBomChild : oldBomList) {
                                                            double should = 0;
                                                            double actual = 0;
                                                            if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                                                if (sysBomChild.getMaterialId().equals("7.Y13A1A000001")
                                                                        || sysBomChild.getMaterialId().equals("7.Y13A1A000002")
                                                                        || sysBomChild.getMaterialId().equals("7.Y18A1A000001")
                                                                        || sysBomChild.getMaterialId().equals("7.Y11A1A100120")
                                                                        || sysBomChild.getMaterialId().equals("7.Y11A1A000349")) {
                                                                    if (sysProductRecord.isHasWeight()) {
                                                                        should = 0;
                                                                        actual = sysProductRecord.getEndWeight1().doubleValue();
                                                                        actual = actual * oP;
                                                                    } else {
                                                                        should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount() * oP;
                                                                        actual = sysBomChild.getHasGetNum() * oP;
                                                                    }

                                                                } else {
//
                                                                }
                                                            } else {
                                                                should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                                                                actual = sysBomChild.getHasGetNum();
                                                            }
                                                            if (hasY > 0 && hasC == 1 && sysBomChild.getMaterialId().startsWith("7.Y")) {
                                                                log.error("有次料，有原料");
                                                                if (sysBomChildG.getMaterialId().equals(sysBomChild.getMaterialId())) {
                                                                    YP = totalYS / totalS;
                                                                    GP = totalGS / totalS;
                                                                    if (sysProductRecord.isTwoWeight()) {
                                                                        if (sysBomChild.getMaterialId().equals("7.Y13A1A000001")
                                                                                || sysBomChild.getMaterialId().equals("7.Y13A1A000002")
                                                                                || sysBomChild.getMaterialId().equals("7.Y18A1A000001")
                                                                                || sysBomChild.getMaterialId().equals("7.Y11A1A100120")
                                                                                || sysBomChild.getMaterialId().equals("7.Y11A1A000349")) {
                                                                            log.error("2称1");
                                                                            should = 0;
                                                                            actual = sysProductRecord.getEndWeight1().doubleValue();
                                                                        } else {
                                                                            log.error("2称2");
                                                                            should = 0;
                                                                            actual = sysProductRecord.getEndWeight2().doubleValue();
                                                                        }

                                                                    } else if (sysProductRecord.isHasWeight()) {
                                                                        actual = sysProductRecord.getEndWeight1().doubleValue();
                                                                        actual = actual * oP;
                                                                        should = 0;
                                                                    } else {
                                                                        should = sysBomChildG.getUnitNum().doubleValue() * sysProductRecord.getTotalCount() * oP;
                                                                        actual = sysBomChildG.getHasGetNum() * oP;
                                                                    }
                                                                    double resultNum = actual - should;
                                                                    log.error("有次料的物料：{},应发：{},实发：{},退：{}", sysBomChildG.getMaterialName(), should, actual, resultNum);
                                                                    if (resultNum > 0) {
                                                                        /*退次*/
                                                                        PickData pickData2 = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChildG, resultNum * GP);
                                                                        KingdeeResult kingdeeResult2 = this.kingdeeUtils.addPick(pickData2);
                                                                        if (kingdeeResult2.getStatusCode() == 200) {
                                                                            saveMaterialRecord(oldWorkPlan, sysBomChildG, -resultNum * GP, pickData2, kingdeeResult2, false);
                                                                        }
                                                                        log.error("包括次料退次");
                                                                        if (sysBomChild.isSame()) {
                                                                            log.error("包括次料领次");
                                                                            PickData pickData3 = this.kingdeeUtils.materialUntilGet(newWorkPlan, sysBomChild.getChildBomChild(), resultNum * GP);
                                                                            KingdeeResult kingdeeResult3 = this.kingdeeUtils.addPick(pickData3);
                                                                            if (kingdeeResult3.getStatusCode() == 200) {
                                                                                saveMaterialRecord(newWorkPlan, sysBomChild.getChildBomChild(), resultNum * GP, pickData3, kingdeeResult3, true);
                                                                            }
                                                                        }
                                                                    } else {
                                                                        log.error("料号：{}，料名：{}无需退料", sysBomChildG.getMaterialId(), sysBomChildG.getMaterialName());
                                                                        log.error("料号：{}，料名：{}无需退料", sysBomChildY.getMaterialId(), sysBomChildY.getMaterialName());
                                                                    }
                                                                } else if (
                                                                        sysBomChildY.getMaterialId().equals(sysBomChild.getMaterialId())
                                                                                && (!sysBomChildY.getMaterialId().equals("7.Y13A1A000001")
                                                                                && !sysBomChildY.getMaterialId().equals("7.Y11A1A000349")
                                                                                && !sysBomChildY.getMaterialId().equals("7.Y18A1A000001")
                                                                                && !sysBomChildY.getMaterialId().equals("7.Y11A1A100120")
                                                                                && !sysBomChildY.getMaterialId().equals("7.Y13A1A000002")
                                                                        )) {
                                                                    YP = totalYS / totalS;
                                                                    GP = totalGS / totalS;
                                                                    if (sysProductRecord.isTwoWeight()) {
                                                                        if (sysBomChild.getMaterialId().equals("7.Y13A1A000001")
                                                                                || sysBomChild.getMaterialId().equals("7.Y13A1A000002")
                                                                                || sysBomChild.getMaterialId().equals("7.Y18A1A000001")
                                                                                || sysBomChild.getMaterialId().equals("7.Y11A1A100120")
                                                                                || sysBomChild.getMaterialId().equals("7.Y11A1A000349")) {
                                                                            log.error("2称1");
                                                                            should = 0;
                                                                            actual = sysProductRecord.getEndWeight1().doubleValue();
                                                                        } else {
                                                                            log.error("2称2");
                                                                            should = 0;
                                                                            actual = sysProductRecord.getEndWeight2().doubleValue();
                                                                        }

                                                                    } else if (sysProductRecord.isHasWeight()) {
                                                                        actual = sysProductRecord.getEndWeight1().doubleValue();
                                                                        actual = actual * oP;
                                                                        should = 0;
                                                                    } else {
                                                                        should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount() * oP;
                                                                        actual = sysBomChild.getHasGetNum() * oP;
                                                                    }
                                                                    double resultNum = actual - should;
                                                                    log.error("有软胶物料：{},应发：{},实发：{},退：{}", sysBomChild.getMaterialName(), should, actual, resultNum);
                                                                    if (resultNum > 0) {
                                                                        /*退原料*/
                                                                        if (sysBomChildY.getMaterialId().startsWith("7.Y")) {
                                                                            PickData pickData = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChildY, resultNum * YP);
                                                                            KingdeeResult kingdeeResult = this.kingdeeUtils.addPick(pickData);
                                                                            if (kingdeeResult.getStatusCode() == 200) {
                                                                                saveMaterialRecord(oldWorkPlan, sysBomChildY, -resultNum * YP, pickData, kingdeeResult, false);
                                                                            }
                                                                        } else {
                                                                            PickData pickData = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChild, resultNum);
                                                                            KingdeeResult kingdeeResult = this.kingdeeUtils.addPick(pickData);
                                                                            if (kingdeeResult.getStatusCode() == 200) {
                                                                                saveMaterialRecord(oldWorkPlan, sysBomChild, -resultNum, pickData, kingdeeResult, false);
                                                                            }
                                                                        }
                                                                        log.error("包括次料退原料");
                                                                        if (sysBomChild.isSame()) {
                                                                            log.error("包括次料领原料");
                                                                            if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                                                                PickData pickData1 = this.kingdeeUtils.materialUntilGet(newWorkPlan, sysBomChild.getChildBomChild(), resultNum * YP);
                                                                                KingdeeResult kingdeeResult1 = this.kingdeeUtils.addPick(pickData1);
                                                                                if (kingdeeResult1.getStatusCode() == 200) {
                                                                                    saveMaterialRecord(newWorkPlan, sysBomChild.getChildBomChild(), resultNum * YP, pickData1, kingdeeResult1, true);
                                                                                }
                                                                            } else {
                                                                                PickData pickData1 = this.kingdeeUtils.materialUntilGet(newWorkPlan, sysBomChild.getChildBomChild(), resultNum);
                                                                                KingdeeResult kingdeeResult1 = this.kingdeeUtils.addPick(pickData1);
                                                                                if (kingdeeResult1.getStatusCode() == 200) {
                                                                                    saveMaterialRecord(newWorkPlan, sysBomChild.getChildBomChild(), resultNum, pickData1, kingdeeResult1, true);
                                                                                }
                                                                            }

                                                                        }
                                                                    } else {
                                                                        log.error("料号：{}，料名：{}无需退料", sysBomChildG.getMaterialId(), sysBomChildG.getMaterialName());
                                                                        log.error("料号：{}，料名：{}无需退料", sysBomChildY.getMaterialId(), sysBomChildY.getMaterialName());
                                                                    }
                                                                } else {
                                                                    double resultNum = actual - should;
                                                                    log.error("物料原料1：{},应发：{},实发：{},退：{}", sysBomChild.getMaterialName(), should, actual, resultNum);
                                                                    if (resultNum > 0) {
                                                                        log.error("不包括次料退");
                                                                        PickData pickData = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChild, resultNum);
                                                                        KingdeeResult kingdeeResult = this.kingdeeUtils.addPick(pickData);
                                                                        if (kingdeeResult.getStatusCode() == 200) {
                                                                            saveMaterialRecord(oldWorkPlan, sysBomChild, -resultNum, pickData, kingdeeResult, false);
                                                                        }
                                                                        if (sysBomChild.isSame()) {
                                                                            log.error("不包括次料领");
                                                                            PickData pickData1 = this.kingdeeUtils.materialUntilGet(newWorkPlan, sysBomChild.getChildBomChild(), resultNum);
                                                                            KingdeeResult kingdeeResult1 = this.kingdeeUtils.addPick(pickData1);
                                                                            if (kingdeeResult1.getStatusCode() == 200) {
                                                                                saveMaterialRecord(newWorkPlan, sysBomChild.getChildBomChild(), resultNum, pickData1, kingdeeResult1, true);
                                                                            }
                                                                        }
                                                                    } else {
                                                                        log.error("料号2：{}，料名：{}无需退料", sysBomChild.getMaterialId(), sysBomChild.getMaterialName());
                                                                    }
                                                                }
                                                            } else {
                                                                log.error("DDDD:{}", sysBomChild);
                                                                if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                                                    log.error("D:原料");
                                                                    if (sysProductRecord.isTwoWeight()) {
                                                                        if (sysBomChild.getMaterialId().equals("7.Y13A1A000001")
                                                                                || sysBomChild.getMaterialId().equals("7.Y13A1A000002")
                                                                                || sysBomChild.getMaterialId().equals("7.Y18A1A000001")
                                                                                || sysBomChild.getMaterialId().equals("7.Y11A1A100120")
                                                                                || sysBomChild.getMaterialId().equals("7.Y11A1A000349")) {
                                                                            log.error("2称1");
                                                                            should = 0;
                                                                            actual = sysProductRecord.getEndWeight1().doubleValue();
                                                                        } else {
                                                                            log.error("2称2");
                                                                            should = 0;
                                                                            actual = sysProductRecord.getEndWeight2().doubleValue();
                                                                        }

                                                                    } else if (sysProductRecord.isHasWeight()) {
                                                                        log.error("D:有");

                                                                        should = 0;
                                                                        actual = sysProductRecord.getEndWeight1().doubleValue();
                                                                        actual = actual * oP;
                                                                    } else {
                                                                        log.error("D:没有");
                                                                        should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount() * oP;
                                                                        actual = sysBomChild.getHasGetNum() * oP;
                                                                    }
                                                                } else {
                                                                    log.error("D:没有1");
                                                                    should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                                                                    actual = sysBomChild.getHasGetNum();
                                                                }
                                                                double resultNum = actual - should;
                                                                log.error("物料1：{},应发1：{},实发1：{},退：{}", sysBomChild.getMaterialName(), should, actual, resultNum);
                                                                if (resultNum > 0) {
                                                                    log.error("不包括次料退");
                                                                    PickData pickData = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChild, resultNum);
                                                                    KingdeeResult kingdeeResult = this.kingdeeUtils.addPick(pickData);
                                                                    if (kingdeeResult.getStatusCode() == 200) {
                                                                        saveMaterialRecord(oldWorkPlan, sysBomChild, -resultNum, pickData, kingdeeResult, false);
                                                                    }
                                                                    if (sysBomChild.isSame()) {
                                                                        log.error("不包括次料领");
                                                                        if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                                                            PickData pickData1 = this.kingdeeUtils.materialUntilGet(newWorkPlan, sysBomChild, resultNum);
                                                                            KingdeeResult kingdeeResult1 = this.kingdeeUtils.addPick(pickData1);
                                                                            if (kingdeeResult1.getStatusCode() == 200) {
                                                                                saveMaterialRecord(newWorkPlan, sysBomChild, resultNum, pickData1, kingdeeResult1, true);
                                                                            }
                                                                        } else {
                                                                            PickData pickData1 = this.kingdeeUtils.materialUntilGet(newWorkPlan, sysBomChild, resultNum);
                                                                            KingdeeResult kingdeeResult1 = this.kingdeeUtils.addPick(pickData1);
                                                                            if (kingdeeResult1.getStatusCode() == 200) {
                                                                                saveMaterialRecord(newWorkPlan, sysBomChild, resultNum, pickData1, kingdeeResult1, true);
                                                                            }
                                                                        }

                                                                    }
                                                                } else {
                                                                    log.error("料号：{}，料名：{}无需退料", sysBomChild.getMaterialId(), sysBomChild.getMaterialName());
                                                                }
                                                            }

                                                        }

                                                        return ResultTool.success();
                                                    }
                                                } catch (Exception e) {
                                                    log.error("Exception:{}", e.getMessage());
                                                    sysProductRecord.setContinue(true);
                                                    sysProductRecord.setNormal(true);
                                                    sysProductRecord.setOver(true);
                                                    sysProductRecord.setStart(true);
                                                    this.sysProductRecordService.updateById(sysProductRecord);
                                                }
                                            } else {
                                                sysProductRecord.setContinue(true);
                                                sysProductRecord.setNormal(true);
                                                sysProductRecord.setOver(true);
                                                sysProductRecord.setStart(true);
                                                this.sysProductRecordService.updateById(sysProductRecord);
                                                return ResultTool.fail();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }


                }

            }
        }
        return null;
    }

    public Result<?> exchange4(List<SysProductRecord> sysProductRecordList) throws IOException {
        for (SysProductRecord sysProductRecord : sysProductRecordList) {
            log.error("WORK:{}", sysProductRecord);
            LocalDate localDate = LocalDate.now();
            LocalDateTime localDateTime = localDate.atTime(0, 0, 0);
            Date startTime = Date.from(localDate.atTime(8, 0, 0).atZone(ZoneId.systemDefault()).toInstant());
            String summary = "手动结束";
            String machineName = sysProductRecord.getMachineName();
            /*查询后续排产工单*/
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.where(SYS_WORK_PLAN.PRODUCT_STATUS.eq(1));
            queryWrapper.where(SYS_WORK_PLAN.MACHINE_NAME.eq(machineName));
            queryWrapper.where(SYS_WORK_PLAN.PLAN_START_TIME.eq(sysProductRecord.getWorkPlan().getPlanStartTime()));
            queryWrapper.orderBy(SYS_WORK_PLAN.WORK_PLAN_ID, true);
            if (sysProductRecord.getWorkPlan().isMoldSame()) {
                queryWrapper.limit(1);
            } else {
                queryWrapper.limit(1);
            }
            List<SysWorkPlan> workPlanList = this.sysWorkPlanService.list(queryWrapper);
            for (SysWorkPlan workPlan : workPlanList) {
                queryWrapper = QueryWrapper.create();
                queryWrapper.where(SYS_BOM.PRODUCT_ICMO_ID.eq(workPlan.getInterId()));
                queryWrapper.orderBy(SYS_BOM.ID, false);
                queryWrapper.limit(1);
                SysBom bom = this.sysBomService.getOne(queryWrapper);
                if (bom != null) {
                    workPlan.setBom(bom);
                }

            }
            log.error("WORKPLANLIST:{}", workPlanList);
            /*没有工单继续生产当前工单*/

            if (workPlanList.size() == 1) {
                /*有工单则将当前生产工单关闭，切换到最近计划开始时间的工单*/
                SysWorkPlan oldWorkPlan = this.sysWorkPlanService.getById(sysProductRecord.getWorkPlanId());
                queryWrapper = QueryWrapper.create();
                queryWrapper.where(SYS_BOM.PRODUCT_ICMO_ID.eq(oldWorkPlan.getInterId()));
                queryWrapper.orderBy(SYS_BOM.ID, false);
                queryWrapper.limit(1);
                SysBom bom = this.sysBomService.getOne(queryWrapper);
                if (bom != null) {
                    oldWorkPlan.setBom(bom);
                }
                sysProductRecord.setNormal(false);
                sysProductRecord.setOver(false);
                sysProductRecord.setContinue(false);
                sysProductRecord.setSummary(summary);
                sysProductRecord.setActualEndTime(new Date());
                sysProductRecord.setEntry(true);
                /*有电子称*/
                if (sysProductRecord.isHasWeight()) {
                    queryWrapper = QueryWrapper.create();
                    queryWrapper.where(SYS_MACHINE_PLC.MACHINE_NAME.eq(sysProductRecord.getMachineName()));
//                    double weight = sysProductRecord.getEndWeight1().doubleValue();
                    SysMachinePlc sysMachinePlc = this.sysMachinePlcService.getOne(queryWrapper);
                    if (sysMachinePlc != null) {
                        sysProductRecord = this.getWeightDataEnd(sysMachinePlc, sysProductRecord);

                    } else {
                        sysProductRecord.setTwoWeight(false);
                        sysProductRecord.setHasWeight(false);
                    }

                } else {
                    sysProductRecord.setTwoWeight(false);
                    sysProductRecord.setHasWeight(false);
                }
                /*更新当前生产记录状态*/
                boolean result = sysProductRecordService.updateById(sysProductRecord);
                if (result) {
                    boolean hasTwoMaterial = false;
                    List<SysBomChild> oldBomList = this.kingdeeUtils.getPPBOMDetail(oldWorkPlan.getBom().getId()).stream().filter(item -> !item.getMaterialId().startsWith("9.")).collect(Collectors.toList());
                    log.error("OldBomList:{}", JSONArray.toJSONString(oldBomList));

                    List<String> ids = new ArrayList<>();
                    ids.add("7.Y13A1A000001");
                    ids.add("7.Y18A1A000001");
                    ids.add("7.Y11A1A000349");
                    ids.add("7.Y13A1A000002");
                    ids.add("7.Y11A1A100120");

                    oldBomList.forEach(oldItem -> {
                        oldItem.setSame(false);
                    });

                    for (SysBomChild sysBomChild : oldBomList) {
                        if (ids.contains(sysBomChild.getMaterialId())) {
                            hasTwoMaterial = true;
                            break;
                        }
                    }

                    double totalYS = 0;//原料标准用量
                    double totalY = 0;//原料已领数量
                    double totalGS = 0;//改性标准用量
                    double totalG = 0;//改性已领数量
                    double totalS = 0;//总标准用量


                    double YP = 0;//
                    double GP = 0;//

                    SysBomChild sysBomChildY = new SysBomChild();
                    SysBomChild sysBomChildG = new SysBomChild();
                    int hasY = 0;
                    int hasC = 0;
                    oldBomList = oldBomList.stream().filter(item -> item.getAuxqtyPick().doubleValue() > 0).collect(Collectors.toList());
                    List<SysBomChild> sysBomChildList = oldBomList.stream().filter(item ->
                            item.getMaterialId().startsWith("7.Y")
                                    && (!item.getMaterialId().equals("7.Y11A1A000349")
                                    && !item.getMaterialId().equals("7.Y13A1A000001")
                                    && !item.getMaterialId().equals("7.Y18A1A000001")
                                    && !item.getMaterialId().equals("7.Y13A1A000002")
                                    && !item.getMaterialId().equals("7.Y11A1A100120")
                            )).collect(Collectors.toList());                                        /*判断是否有改性料并添加表四*/
                    for (SysBomChild sysBomChild : sysBomChildList) {
                        String materialName = sysBomChild.getMaterialName();
                        if ((materialName.contains("改性") || materialName.contains("抽粒") || materialName.contains("次料")) && sysBomChild.getAuxqtyPick().doubleValue() > 0) {
                            totalG += sysBomChild.getHasGetNum();
                            totalGS = sysBomChild.getStandardNum().doubleValue();
                            sysBomChild.setG(true);
                            sysBomChildG = sysBomChild;
                            hasC++;
                        } else if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                            hasY++;
                            sysBomChildY = sysBomChild;
                            totalY += sysBomChild.getHasGetNum();
                            totalYS = sysBomChild.getStandardNum().doubleValue();
                        }
                        totalS += sysBomChild.getStandardNum().doubleValue();
                    }
                    /*遍历投料单判断*/
                    for (SysBomChild sysBomChild : oldBomList) {
                        double should = 0;
                        double actual = 0;
                        if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                            if (sysBomChild.getMaterialId().equals("7.Y13A1A000001")
                                    || sysBomChild.getMaterialId().equals("7.Y13A1A000002")
                                    || sysBomChild.getMaterialId().equals("7.Y18A1A000001")
                                    || sysBomChild.getMaterialId().equals("7.Y11A1A100120")
                                    || sysBomChild.getMaterialId().equals("7.Y11A1A000349")) {
                                if (sysProductRecord.isHasWeight()) {
                                    should = 0;
                                    actual = sysProductRecord.getEndWeight1().doubleValue();
                                } else {
                                    should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                                    actual = sysBomChild.getHasGetNum();
                                }

                            } else {
                                if (hasTwoMaterial) {
                                    if (sysProductRecord.isTwoWeight()) {
                                        should = 0;
                                        actual = sysProductRecord.getEndWeight2().doubleValue();
                                    } else {
                                        should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                                        actual = sysBomChild.getHasGetNum();
                                    }
                                } else {
                                    if (sysProductRecord.isHasWeight()) {
                                        should = 0;
                                        actual = sysProductRecord.getEndWeight1().doubleValue();
                                    } else {
                                        should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                                        actual = sysBomChild.getHasGetNum();
                                    }
                                }

                            }
                        } else {
                            should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                            actual = sysBomChild.getHasGetNum();
                        }
                        log.error("516应发：{}，已发：{}", should, actual);
                        if (hasY > 0 && hasC == 1 && sysBomChild.getMaterialId().startsWith("7.Y")) {
                            log.error("有次料，有原料");
                            if (sysBomChildG.getMaterialId().equals(sysBomChild.getMaterialId())) {
                                YP = totalYS / totalS;
                                GP = totalGS / totalS;
                                if (sysProductRecord.isHasWeight()) {
                                    actual = sysProductRecord.getEndWeight1().doubleValue();
                                    should = 0;
                                } else {
                                    should = sysBomChildG.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                                    actual = sysBomChildG.getHasGetNum();
                                }
                                double resultNum = actual - should;
                                log.error("有次料的物料：{},应发：{},实发：{},退：{}", sysBomChildG.getMaterialName(), should, actual, resultNum);
                                if (resultNum > 0) {
                                    /*退次*/
                                    PickData pickData2 = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChildG, resultNum * GP);
                                    KingdeeResult kingdeeResult2 = this.kingdeeUtils.addPick(pickData2);
                                    if (kingdeeResult2.getStatusCode() == 200) {
                                        saveMaterialRecord(oldWorkPlan, sysBomChildG, -resultNum * GP, pickData2, kingdeeResult2, false);
                                    }


                                } else {
                                    log.error("料号：{}，料名：{}无需退料", sysBomChildG.getMaterialId(), sysBomChildG.getMaterialName());
                                    log.error("料号：{}，料名：{}无需退料", sysBomChildY.getMaterialId(), sysBomChildY.getMaterialName());
                                }
                            } else if (
                                    sysBomChildY.getMaterialId().equals(sysBomChild.getMaterialId())
                                            && (!sysBomChildY.getMaterialId().equals("7.Y13A1A000001")
                                            && !sysBomChildY.getMaterialId().equals("7.Y18A1A000001")
                                            && !sysBomChildY.getMaterialId().equals("7.Y11A1A000349")
                                            && !sysBomChildY.getMaterialId().equals("7.Y11A1A100120")
                                            && !sysBomChildY.getMaterialId().equals("7.Y13A1A000002")
                                    )) {
                                YP = totalYS / totalS;
                                GP = totalGS / totalS;
                                if (sysProductRecord.isTwoWeight()) {
                                    if (sysBomChild.getMaterialId().equals("7.Y13A1A000001")
                                            || sysBomChild.getMaterialId().equals("7.Y13A1A000002")
                                            || sysBomChild.getMaterialId().equals("7.Y18A1A000001")
                                            || sysBomChild.getMaterialId().equals("7.Y11A1A100120")
                                            || sysBomChild.getMaterialId().equals("7.Y11A1A000349")) {
                                        log.error("2称1");
                                        should = 0;
                                        actual = sysProductRecord.getEndWeight1().doubleValue();
                                    } else {
                                        log.error("2称2");
                                        should = 0;
                                        actual = sysProductRecord.getEndWeight2().doubleValue();
                                    }

                                } else if (sysProductRecord.isHasWeight()) {
                                    actual = sysProductRecord.getEndWeight1().doubleValue();
                                    should = 0;
                                } else {
                                    should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                                    actual = sysBomChild.getHasGetNum();
                                }
                                double resultNum = actual - should;
                                log.error("有软胶物料：{},应发：{},实发：{},退：{}", sysBomChild.getMaterialName(), should, actual, resultNum);

                                if (resultNum > 0) {
                                    /*退原料*/
                                    if (sysBomChildY.getMaterialId().startsWith("7.Y")) {
                                        PickData pickData = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChildY, resultNum * YP);
                                        KingdeeResult kingdeeResult = this.kingdeeUtils.addPick(pickData);
                                        if (kingdeeResult.getStatusCode() == 200) {
                                            saveMaterialRecord(oldWorkPlan, sysBomChildY, -resultNum * YP, pickData, kingdeeResult, false);
                                        }
                                    } else {
                                        PickData pickData = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChild, resultNum);
                                        KingdeeResult kingdeeResult = this.kingdeeUtils.addPick(pickData);
                                        if (kingdeeResult.getStatusCode() == 200) {
                                            saveMaterialRecord(oldWorkPlan, sysBomChild, -resultNum, pickData, kingdeeResult, false);
                                        }
                                    }

                                } else {
                                    log.error("料号：{}，料名：{}无需退料", sysBomChildG.getMaterialId(), sysBomChildG.getMaterialName());
                                    log.error("料号：{}，料名：{}无需退料", sysBomChildY.getMaterialId(), sysBomChildY.getMaterialName());
                                }
                            } else {
                                double resultNum = actual - should;
                                log.error("物料原料1：{},应发：{},实发：{},退：{}", sysBomChild.getMaterialName(), should, actual, resultNum);
                                if (resultNum > 0) {
                                    log.error("不包括次料退");
                                    PickData pickData = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChild, resultNum);
                                    KingdeeResult kingdeeResult = this.kingdeeUtils.addPick(pickData);
                                    if (kingdeeResult.getStatusCode() == 200) {
                                        saveMaterialRecord(oldWorkPlan, sysBomChild, -resultNum, pickData, kingdeeResult, false);
                                    }

                                } else {
                                    log.error("料号2：{}，料名：{}无需退料", sysBomChild.getMaterialId(), sysBomChild.getMaterialName());
                                }
                            }
                        } else {
                            log.error("DDDD:{}", sysBomChild);
                            if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                if (sysProductRecord.isTwoWeight()) {
                                    if (sysBomChild.getMaterialId().equals("7.Y13A1A000001")
                                            || sysBomChild.getMaterialId().equals("7.Y13A1A000002")
                                            || sysBomChild.getMaterialId().equals("7.Y18A1A000001")
                                            || sysBomChild.getMaterialId().equals("7.Y11A1A100120")
                                            || sysBomChild.getMaterialId().equals("7.Y11A1A000349")) {
                                        log.error("2称1");
                                        should = 0;
                                        actual = sysProductRecord.getEndWeight1().doubleValue();
                                    } else {
                                        log.error("2称2");
                                        should = 0;
                                        actual = sysProductRecord.getEndWeight2().doubleValue();
                                    }

                                } else if (sysProductRecord.isHasWeight()) {
                                    log.error("1称");
                                    should = 0;
                                    actual = sysProductRecord.getEndWeight1().doubleValue();
                                } else {
                                    log.error("0称");
                                    should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                                    actual = sysBomChild.getHasGetNum();
                                }
                            } else {
                                should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                                actual = sysBomChild.getHasGetNum();
                            }
                            double resultNum = actual - should;
                            log.error("物料1：{},应发1：{},实发1：{},退：{}", sysBomChild.getMaterialName(), should, actual, resultNum);
                            if (resultNum > 0) {
                                log.error("不包括次料退");
                                PickData pickData = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChild, resultNum);
                                KingdeeResult kingdeeResult = this.kingdeeUtils.addPick(pickData);
                                if (kingdeeResult.getStatusCode() == 200) {
                                    saveMaterialRecord(oldWorkPlan, sysBomChild, -resultNum, pickData, kingdeeResult, false);
                                }
                            } else {
                                log.error("料号：{}，料名：{}无需退料", sysBomChild.getMaterialId(), sysBomChild.getMaterialName());
                            }
                        }

                    }

                    return ResultTool.success();
                    /*更新当前生产工单状态*/
                }

            }
            else if (workPlanList.size() == 2) {
                localDate = LocalDate.now().minusDays(1);
                localDateTime = localDate.atTime(0, 0, 0);
                queryWrapper = QueryWrapper.create();
//                queryWrapper.where(SYS_WORK_PLAN.PRODUCT_STATUS.eq(1));
//                queryWrapper.where(SYS_WORK_PLAN.MACHINE_NAME.eq(machineName));
//                queryWrapper.where(SYS_WORK_PLAN.PLAN_START_TIME.eq(localDateTime));
                queryWrapper.where(SYS_WORK_PLAN.WORK_PLAN_ID.eq(workPlanList.get(0).getWorkPlanId()).or(SYS_WORK_PLAN.WORK_PLAN_ID.eq(workPlanList.get(1).getWorkPlanId())));
                queryWrapper.orderBy(SYS_WORK_PLAN.WORK_PLAN_ID, true);
                queryWrapper.limit(2);
                List<SysWorkPlan> oldWokPlanList = this.sysWorkPlanService.getMapper().selectListWithRelationsByQuery(queryWrapper);
                for (SysWorkPlan workPlan : oldWokPlanList) {
                    queryWrapper = QueryWrapper.create();
                    queryWrapper.where(SYS_BOM.PRODUCT_ICMO_ID.eq(workPlan.getInterId()));
                    queryWrapper.orderBy(SYS_BOM.ID, false);
                    queryWrapper.limit(1);
                    SysBom bom = this.sysBomService.getOne(queryWrapper);
                    if (bom != null) {
                        workPlan.setBom(bom);
                    }

                }
                log.error("OLD:{}", oldWokPlanList);
                if (oldWokPlanList.size() == 2) {
                    SysWorkPlan oldWorkPlan1 = oldWokPlanList.get(0);
                    SysWorkPlan oldWorkPlan2 = oldWokPlanList.get(1);

                    if (oldWorkPlan1.isMoldSame() && oldWorkPlan2.isMoldSame()) {

                        List<SysBomChild> oldBomChildList1 = this.kingdeeUtils.getPPBOMDetail(oldWorkPlan1.getBom().getId());
                        List<SysBomChild> oldBomChildList2 = this.kingdeeUtils.getPPBOMDetail(oldWorkPlan2.getBom().getId());


                        double nTotal = 0;
                        double oTotal = 0;
                        double nY1 = 0;
                        double nY2 = 0;
                        double oY1 = 0;
                        double oY2 = 0;
                        for (SysBomChild sysBomChild : oldBomChildList1) {
                            if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                oY1 += sysBomChild.getStandardNum().doubleValue();
                                oTotal += sysBomChild.getStandardNum().doubleValue();
                            }

                        }
                        for (SysBomChild sysBomChild : oldBomChildList2) {
                            if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                oY2 += sysBomChild.getStandardNum().doubleValue();
                                oTotal += sysBomChild.getStandardNum().doubleValue();

                            }
                        }

                        DecimalFormat df = new DecimalFormat("#.##");
                        log.error("Old1:{},New1:{}", oY1, nY1);
                        log.error("Old2:{},New2:{}", oY2, nY2);
                        log.error("Old2:{},New2:{}", oTotal, nTotal);
                        double oldP1 = Double.parseDouble(df.format(oY1 / oTotal));
                        double oldP2 = Double.parseDouble(df.format(oY2 / oTotal));

                        if (oldP1 != 0 && oldP2 != 0) {
                            SysWorkPlan workPlan = sysProductRecord.getWorkPlan();
                            SysWorkPlan oldWorkPlan = null;
                            List<SysBomChild> oldBomList = new ArrayList<>();
                            List<SysBomChild> newBomList = new ArrayList<>();
                            double oP = 1;
                            double nP = 1;
                            if (workPlan.getProductId().equals(oldWorkPlan1.getProductId())) {

                                oldWorkPlan = oldWorkPlan1;
                                log.error("工单1:{}", oldWorkPlan);
                                oP = oldP1;
                                oldBomList = oldBomChildList1.stream().filter(item -> !item.getMaterialId().startsWith("9.")).collect(Collectors.toList());
                                log.error("OldBomList:{}", JSONArray.toJSONString(oldBomList));
                            } else if (workPlan.getProductId().equals(oldWorkPlan2.getProductId())) {

                                oldWorkPlan = oldWorkPlan2;
                                log.error("工单2:{}", oldWorkPlan);
                                oldBomList = oldBomChildList2.stream().filter(item -> !item.getMaterialId().startsWith("9.")).collect(Collectors.toList());
                                oP = oldP2;
                            }
                            if (oldWorkPlan != null) {
                                /*有工单则将当前生产工单关闭，切换到最近计划开始时间的工单*/
                                queryWrapper = QueryWrapper.create();
                                queryWrapper.where(SYS_BOM.PRODUCT_ICMO_ID.eq(oldWorkPlan.getInterId()));
                                queryWrapper.orderBy(SYS_BOM.ID, false);
                                queryWrapper.limit(1);
                                SysBom bom = this.sysBomService.getOne(queryWrapper);
                                if (bom != null) {
                                    oldWorkPlan.setBom(bom);
                                }
                                sysProductRecord.setNormal(false);
                                sysProductRecord.setOver(false);
                                sysProductRecord.setContinue(false);
                                sysProductRecord.setSummary(summary);
                                sysProductRecord.setActualEndTime(new Date());
                                sysProductRecord.setEntry(true);
                                /*有电子称*/
                                if (sysProductRecord.isHasWeight()) {
                                    queryWrapper = QueryWrapper.create();
                                    queryWrapper.where(SYS_MACHINE_PLC.MACHINE_NAME.eq(sysProductRecord.getMachineName()));
//                                                double weight=sysProductRecord.getEndWeight1().doubleValue();
                                    SysMachinePlc sysMachinePlc = this.sysMachinePlcService.getOne(queryWrapper);
                                    if (sysMachinePlc != null) {
                                        sysProductRecord = this.getWeightDataEnd(sysMachinePlc, sysProductRecord);

                                    } else {
                                        sysProductRecord.setTwoWeight(false);
                                        sysProductRecord.setHasWeight(false);
                                    }
                                } else {
                                    sysProductRecord.setTwoWeight(false);
                                    sysProductRecord.setHasWeight(false);
                                }

                                /*更新当前生产记录状态*/
                                sysProductRecord.setEndUserName("SYSTEM1");
                                sysProductRecord.setEndUserId("SYSTEM1");
                                boolean result = sysProductRecordService.updateById(sysProductRecord);
                                if (result) {


                                    oldBomList.forEach(oldItem -> {
                                        oldItem.setSame(false);
                                    });


                                    double totalYS = 0;//原料标准用量
                                    double totalY = 0;//原料已领数量
                                    double totalGS = 0;//改性标准用量
                                    double totalG = 0;//改性已领数量
                                    double totalS = 0;//总标准用量


                                    double YP = 0;//
                                    double GP = 0;//

                                    SysBomChild sysBomChildY = new SysBomChild();
                                    SysBomChild sysBomChildG = new SysBomChild();
                                    int hasY = 0;
                                    int hasC = 0;
                                    oldBomList = oldBomList.stream().filter(item -> item.getAuxqtyPick().doubleValue() > 0).collect(Collectors.toList());
                                    List<SysBomChild> sysBomChildList = oldBomList.stream().filter(item ->
                                            item.getMaterialId().startsWith("7.Y")
                                                    && (!item.getMaterialId().equals("7.Y11A1A000349")
                                                    && !item.getMaterialId().equals("7.Y13A1A000001")
                                                    && !item.getMaterialId().equals("7.Y18A1A000001")
                                                    && !item.getMaterialId().equals("7.Y13A1A000002")
                                                    && !item.getMaterialId().equals("7.Y11A1A100120")
                                            )).collect(Collectors.toList());                                                        /*判断是否有改性料并添加表四*/
                                    for (SysBomChild sysBomChild : sysBomChildList) {
                                        String materialName = sysBomChild.getMaterialName();
                                        if ((materialName.contains("改性") || materialName.contains("抽粒") || materialName.contains("次料")) && sysBomChild.getAuxqtyPick().doubleValue() > 0) {
                                            totalG += sysBomChild.getHasGetNum();
                                            totalGS = sysBomChild.getStandardNum().doubleValue();
                                            sysBomChild.setG(true);
                                            sysBomChildG = sysBomChild;
                                            hasC++;
                                        } else if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                            hasY++;
                                            sysBomChildY = sysBomChild;
                                            totalY += sysBomChild.getHasGetNum();
                                            totalYS = sysBomChild.getStandardNum().doubleValue();
                                        }
                                        totalS += sysBomChild.getStandardNum().doubleValue();
                                    }
                                    /*遍历投料单判断*/
                                    for (SysBomChild sysBomChild : oldBomList) {
                                        double should = 0;
                                        double actual = 0;
                                        if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                            if (sysBomChild.getMaterialId().equals("7.Y13A1A000001")
                                                    || sysBomChild.getMaterialId().equals("7.Y13A1A000002")
                                                    || sysBomChild.getMaterialId().equals("7.Y18A1A000001")
                                                    || sysBomChild.getMaterialId().equals("7.Y11A1A100120")
                                                    || sysBomChild.getMaterialId().equals("7.Y11A1A000349")) {
                                                if (sysProductRecord.isTwoWeight()) {
                                                    if (sysBomChild.getMaterialId().equals("7.Y13A1A000001")
                                                            || sysBomChild.getMaterialId().equals("7.Y13A1A000002")
                                                            || sysBomChild.getMaterialId().equals("7.Y18A1A000001")
                                                            || sysBomChild.getMaterialId().equals("7.Y11A1A100120")
                                                            || sysBomChild.getMaterialId().equals("7.Y11A1A000349")) {
                                                        log.error("2称1");
                                                        should = 0;
                                                        actual = sysProductRecord.getEndWeight1().doubleValue();
                                                    } else {
                                                        log.error("2称2");
                                                        should = 0;
                                                        actual = sysProductRecord.getEndWeight2().doubleValue();
                                                    }

                                                } else if (sysProductRecord.isHasWeight()) {
                                                    should = 0;
                                                    actual = sysProductRecord.getEndWeight1().doubleValue();
                                                    actual = actual * oP;
                                                } else {
                                                    should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount() * oP;
                                                    actual = sysBomChild.getHasGetNum() * oP;
                                                }

                                            } else {
//
                                            }
                                        } else {
                                            should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                                            actual = sysBomChild.getHasGetNum();
                                        }
                                        if (hasY > 0 && hasC == 1 && sysBomChild.getMaterialId().startsWith("7.Y")) {
                                            log.error("有次料，有原料");
                                            if (sysBomChildG.getMaterialId().equals(sysBomChild.getMaterialId())) {
                                                YP = totalYS / totalS;
                                                GP = totalGS / totalS;
                                                if (sysProductRecord.isTwoWeight()) {
                                                    if (sysBomChild.getMaterialId().equals("7.Y13A1A000001")
                                                            || sysBomChild.getMaterialId().equals("7.Y13A1A000002")
                                                            || sysBomChild.getMaterialId().equals("7.Y18A1A000001")
                                                            || sysBomChild.getMaterialId().equals("7.Y11A1A100120")
                                                            || sysBomChild.getMaterialId().equals("7.Y11A1A000349")) {
                                                        log.error("2称1");
                                                        should = 0;
                                                        actual = sysProductRecord.getEndWeight1().doubleValue();
                                                    } else {
                                                        log.error("2称2");
                                                        should = 0;
                                                        actual = sysProductRecord.getEndWeight2().doubleValue();
                                                    }

                                                }else if (sysProductRecord.isHasWeight()) {
                                                    actual = sysProductRecord.getEndWeight1().doubleValue();
                                                    actual = actual * oP;
                                                    should = 0;
                                                } else {
                                                    should = sysBomChildG.getUnitNum().doubleValue() * sysProductRecord.getTotalCount() * oP;
                                                    actual = sysBomChildG.getHasGetNum() * oP;
                                                }
                                                double resultNum = actual - should;
                                                log.error("有次料的物料：{},应发：{},实发：{},退：{}", sysBomChildG.getMaterialName(), should, actual, resultNum);
                                                if (resultNum > 0) {
                                                    /*退次*/
                                                    PickData pickData2 = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChildG, resultNum * GP);
                                                    KingdeeResult kingdeeResult2 = this.kingdeeUtils.addPick(pickData2);
                                                    if (kingdeeResult2.getStatusCode() == 200) {
                                                        saveMaterialRecord(oldWorkPlan, sysBomChildG, -resultNum * GP, pickData2, kingdeeResult2, false);
                                                    }
                                                    log.error("包括次料退次");

                                                } else {
                                                    log.error("料号：{}，料名：{}无需退料", sysBomChildG.getMaterialId(), sysBomChildG.getMaterialName());
                                                    log.error("料号：{}，料名：{}无需退料", sysBomChildY.getMaterialId(), sysBomChildY.getMaterialName());
                                                }
                                            } else if (
                                                    sysBomChildY.getMaterialId().equals(sysBomChild.getMaterialId())
                                                            && (!sysBomChildY.getMaterialId().equals("7.Y13A1A000001")
                                                            && !sysBomChildY.getMaterialId().equals("7.Y18A1A000001")
                                                            && !sysBomChildY.getMaterialId().equals("7.Y11A1A000349")
                                                            && !sysBomChildY.getMaterialId().equals("7.Y11A1A100120")
                                                            && !sysBomChildY.getMaterialId().equals("7.Y13A1A000002")
                                                    )) {
                                                YP = totalYS / totalS;
                                                GP = totalGS / totalS;
                                                if (sysProductRecord.isTwoWeight()) {
                                                    if (sysBomChild.getMaterialId().equals("7.Y13A1A000001")
                                                            || sysBomChild.getMaterialId().equals("7.Y13A1A000002")
                                                            || sysBomChild.getMaterialId().equals("7.Y18A1A000001")
                                                            || sysBomChild.getMaterialId().equals("7.Y11A1A100120")
                                                            || sysBomChild.getMaterialId().equals("7.Y11A1A000349")) {
                                                        log.error("2称1");
                                                        should = 0;
                                                        actual = sysProductRecord.getEndWeight1().doubleValue();
                                                    } else {
                                                        log.error("2称2");
                                                        should = 0;
                                                        actual = sysProductRecord.getEndWeight2().doubleValue();
                                                    }

                                                }else if (sysProductRecord.isHasWeight()) {
                                                    actual = sysProductRecord.getEndWeight1().doubleValue();
                                                    actual = actual * oP;
                                                    should = 0;
                                                } else {
                                                    should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount() * oP;
                                                    actual = sysBomChild.getHasGetNum() * oP;
                                                }
                                                double resultNum = actual - should;
                                                log.error("有软胶物料：{},应发：{},实发：{},退：{}", sysBomChild.getMaterialName(), should, actual, resultNum);
                                                if (resultNum > 0) {
                                                    /*退原料*/
                                                    if (sysBomChildY.getMaterialId().startsWith("7.Y")) {
                                                        PickData pickData = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChildY, resultNum * YP);
                                                        KingdeeResult kingdeeResult = this.kingdeeUtils.addPick(pickData);
                                                        if (kingdeeResult.getStatusCode() == 200) {
                                                            saveMaterialRecord(oldWorkPlan, sysBomChildY, -resultNum * YP, pickData, kingdeeResult, false);
                                                        }
                                                    } else {
                                                        PickData pickData = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChild, resultNum);
                                                        KingdeeResult kingdeeResult = this.kingdeeUtils.addPick(pickData);
                                                        if (kingdeeResult.getStatusCode() == 200) {
                                                            saveMaterialRecord(oldWorkPlan, sysBomChild, -resultNum, pickData, kingdeeResult, false);
                                                        }
                                                    }
                                                    log.error("包括次料退原料");

                                                } else {
                                                    log.error("料号：{}，料名：{}无需退料", sysBomChildG.getMaterialId(), sysBomChildG.getMaterialName());
                                                    log.error("料号：{}，料名：{}无需退料", sysBomChildY.getMaterialId(), sysBomChildY.getMaterialName());
                                                }
                                            } else {
                                                double resultNum = actual - should;
                                                log.error("物料原料1：{},应发：{},实发：{},退：{}", sysBomChild.getMaterialName(), should, actual, resultNum);
                                                if (resultNum > 0) {
                                                    log.error("不包括次料退");
                                                    PickData pickData = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChild, resultNum);
                                                    KingdeeResult kingdeeResult = this.kingdeeUtils.addPick(pickData);
                                                    if (kingdeeResult.getStatusCode() == 200) {
                                                        saveMaterialRecord(oldWorkPlan, sysBomChild, -resultNum, pickData, kingdeeResult, false);
                                                    }

                                                } else {
                                                    log.error("料号2：{}，料名：{}无需退料", sysBomChild.getMaterialId(), sysBomChild.getMaterialName());
                                                }
                                            }
                                        } else {
                                            log.error("DDDD:{}", sysBomChild);
                                            if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                                log.error("D:原料");
                                                if (sysProductRecord.isTwoWeight()) {
                                                    if (sysBomChild.getMaterialId().equals("7.Y13A1A000001")
                                                            || sysBomChild.getMaterialId().equals("7.Y13A1A000002")
                                                            || sysBomChild.getMaterialId().equals("7.Y18A1A000001")
                                                            || sysBomChild.getMaterialId().equals("7.Y11A1A100120")
                                                            || sysBomChild.getMaterialId().equals("7.Y11A1A000349")) {
                                                        log.error("2称1");
                                                        should = 0;
                                                        actual = sysProductRecord.getEndWeight1().doubleValue();
                                                    } else {
                                                        log.error("2称2");
                                                        should = 0;
                                                        actual = sysProductRecord.getEndWeight2().doubleValue();
                                                    }

                                                }else  if (sysProductRecord.isHasWeight()) {
                                                    log.error("D:有");

                                                    should = 0;
                                                    actual = sysProductRecord.getEndWeight1().doubleValue();
                                                    actual = actual * oP;
                                                } else {
                                                    log.error("D:没有");
                                                    should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount() * oP;
                                                    actual = sysBomChild.getHasGetNum() * oP;
                                                }
                                            } else {
                                                log.error("D:没有1");
                                                should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                                                actual = sysBomChild.getHasGetNum();
                                            }
                                            double resultNum = actual - should;
                                            log.error("物料1：{},应发1：{},实发1：{},退：{}", sysBomChild.getMaterialName(), should, actual, resultNum);
                                            if (resultNum > 0) {
                                                log.error("不包括次料退");
                                                PickData pickData = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChild, resultNum);
                                                KingdeeResult kingdeeResult = this.kingdeeUtils.addPick(pickData);
                                                if (kingdeeResult.getStatusCode() == 200) {
                                                    saveMaterialRecord(oldWorkPlan, sysBomChild, -resultNum, pickData, kingdeeResult, false);
                                                }

                                            } else {
                                                log.error("料号：{}，料名：{}无需退料", sysBomChild.getMaterialId(), sysBomChild.getMaterialName());
                                            }
                                        }

                                    }

                                    return ResultTool.success();
                                }
                            } else {
                                sysProductRecord.setContinue(true);
                                sysProductRecord.setNormal(true);
                                sysProductRecord.setOver(true);
                                sysProductRecord.setStart(true);
                                return ResultTool.fail();
//                                                this.sysProductRecordService.updateById(sysProductRecord);
                            }
                        }
                    }

                }

            }
            else {
                /*有工单则将当前生产工单关闭，切换到最近计划开始时间的工单*/
                SysWorkPlan oldWorkPlan = this.sysWorkPlanService.getById(sysProductRecord.getWorkPlanId());
                queryWrapper = QueryWrapper.create();
                queryWrapper.where(SYS_BOM.PRODUCT_ICMO_ID.eq(oldWorkPlan.getInterId()));
                queryWrapper.orderBy(SYS_BOM.ID, false);
                queryWrapper.limit(1);
                SysBom bom = this.sysBomService.getOne(queryWrapper);
                if (bom != null) {
                    oldWorkPlan.setBom(bom);
                }
                sysProductRecord.setNormal(false);
                sysProductRecord.setOver(false);
                sysProductRecord.setContinue(false);
                sysProductRecord.setSummary(summary);
                sysProductRecord.setActualEndTime(new Date());
                sysProductRecord.setEntry(true);
                /*有电子称*/
                if (sysProductRecord.isHasWeight()) {
                    queryWrapper = QueryWrapper.create();
                    queryWrapper.where(SYS_MACHINE_PLC.MACHINE_NAME.eq(sysProductRecord.getMachineName()));
//                    double weight = sysProductRecord.getEndWeight1().doubleValue();
                    SysMachinePlc sysMachinePlc = this.sysMachinePlcService.getOne(queryWrapper);
                    if (sysMachinePlc != null) {
                        sysProductRecord = this.getWeightDataEnd(sysMachinePlc, sysProductRecord);

                    } else {
                        sysProductRecord.setTwoWeight(false);
                        sysProductRecord.setHasWeight(false);
                    }

                } else {
                    sysProductRecord.setTwoWeight(false);
                    sysProductRecord.setHasWeight(false);
                }
                /*更新当前生产记录状态*/
                boolean result = sysProductRecordService.updateById(sysProductRecord);
                if (result) {


                    boolean hasTwoMaterial = false;
                    List<SysBomChild> oldBomList = this.kingdeeUtils.getPPBOMDetail(oldWorkPlan.getBom().getId()).stream().filter(item -> !item.getMaterialId().startsWith("9.")).collect(Collectors.toList());
                    log.error("OldBomList:{}", JSONArray.toJSONString(oldBomList));

                    List<String> ids = new ArrayList<>();
                    ids.add("7.Y13A1A000001");
                    ids.add("7.Y18A1A000001");
                    ids.add("7.Y11A1A000349");
                    ids.add("7.Y13A1A000002");
                    ids.add("7.Y11A1A100120");

                    oldBomList.forEach(oldItem -> {
                        oldItem.setSame(false);
                    });

                    for (SysBomChild sysBomChild : oldBomList) {
                        if (ids.contains(sysBomChild.getMaterialId())) {
                            hasTwoMaterial = true;
                            break;
                        }
                    }

                    double totalYS = 0;//原料标准用量
                    double totalY = 0;//原料已领数量
                    double totalGS = 0;//改性标准用量
                    double totalG = 0;//改性已领数量
                    double totalS = 0;//总标准用量


                    double YP = 0;//
                    double GP = 0;//

                    SysBomChild sysBomChildY = new SysBomChild();
                    SysBomChild sysBomChildG = new SysBomChild();
                    int hasY = 0;
                    int hasC = 0;
                    oldBomList = oldBomList.stream().filter(item -> item.getAuxqtyPick().doubleValue() > 0).collect(Collectors.toList());
                    List<SysBomChild> sysBomChildList = oldBomList.stream().filter(item ->
                            item.getMaterialId().startsWith("7.Y")
                                    && (!item.getMaterialId().equals("7.Y11A1A000349")
                                    && !item.getMaterialId().equals("7.Y13A1A000001")
                                    && !item.getMaterialId().equals("7.Y18A1A000001")
                                    && !item.getMaterialId().equals("7.Y13A1A000002")
                                    && !item.getMaterialId().equals("7.Y11A1A100120")
                            )).collect(Collectors.toList());                                        /*判断是否有改性料并添加表四*/
                    for (SysBomChild sysBomChild : sysBomChildList) {
                        String materialName = sysBomChild.getMaterialName();
                        if ((materialName.contains("改性") || materialName.contains("抽粒") || materialName.contains("次料")) && sysBomChild.getAuxqtyPick().doubleValue() > 0) {
                            totalG += sysBomChild.getHasGetNum();
                            totalGS = sysBomChild.getStandardNum().doubleValue();
                            sysBomChild.setG(true);
                            sysBomChildG = sysBomChild;
                            hasC++;
                        } else if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                            hasY++;
                            sysBomChildY = sysBomChild;
                            totalY += sysBomChild.getHasGetNum();
                            totalYS = sysBomChild.getStandardNum().doubleValue();
                        }
                        totalS += sysBomChild.getStandardNum().doubleValue();
                    }
                    /*遍历投料单判断*/
                    for (SysBomChild sysBomChild : oldBomList) {
                        double should = 0;
                        double actual = 0;
                        if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                            if (sysBomChild.getMaterialId().equals("7.Y13A1A000001")
                                    || sysBomChild.getMaterialId().equals("7.Y13A1A000002")
                                    || sysBomChild.getMaterialId().equals("7.Y18A1A000001")
                                    || sysBomChild.getMaterialId().equals("7.Y11A1A100120")
                                    || sysBomChild.getMaterialId().equals("7.Y11A1A000349")) {
                                if (sysProductRecord.isHasWeight()) {
                                    should = 0;
                                    actual = sysProductRecord.getEndWeight1().doubleValue();
                                } else {
                                    should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                                    actual = sysBomChild.getHasGetNum();
                                }

                            } else {
                                if (hasTwoMaterial) {
                                    if (sysProductRecord.isTwoWeight()) {
                                        should = 0;
                                        actual = sysProductRecord.getEndWeight2().doubleValue();
                                    } else {
                                        should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                                        actual = sysBomChild.getHasGetNum();
                                    }
                                } else {
                                    if (sysProductRecord.isHasWeight()) {
                                        should = 0;
                                        actual = sysProductRecord.getEndWeight1().doubleValue();
                                    } else {
                                        should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                                        actual = sysBomChild.getHasGetNum();
                                    }
                                }

                            }
                        } else {
                            should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                            actual = sysBomChild.getHasGetNum();
                        }
                        log.error("516应发：{}，已发：{}", should, actual);
                        if (hasY > 0 && hasC == 1 && sysBomChild.getMaterialId().startsWith("7.Y")) {
                            log.error("有次料，有原料");
                            if (sysBomChildG.getMaterialId().equals(sysBomChild.getMaterialId())) {
                                YP = totalYS / totalS;
                                GP = totalGS / totalS;
                                if (sysProductRecord.isTwoWeight()) {
                                    if (sysBomChild.getMaterialId().equals("7.Y13A1A000001")
                                            || sysBomChild.getMaterialId().equals("7.Y13A1A000002")
                                            || sysBomChild.getMaterialId().equals("7.Y18A1A000001")
                                            || sysBomChild.getMaterialId().equals("7.Y11A1A100120")
                                            || sysBomChild.getMaterialId().equals("7.Y11A1A000349")) {
                                        log.error("2称1");
                                        should = 0;
                                        actual = sysProductRecord.getEndWeight1().doubleValue();
                                    } else {
                                        log.error("2称2");
                                        should = 0;
                                        actual = sysProductRecord.getEndWeight2().doubleValue();
                                    }

                                }else  if (sysProductRecord.isHasWeight()) {
                                    actual = sysProductRecord.getEndWeight1().doubleValue();
                                    should = 0;
                                } else {
                                    should = sysBomChildG.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                                    actual = sysBomChildG.getHasGetNum();
                                }
                                double resultNum = actual - should;
                                log.error("有次料的物料：{},应发：{},实发：{},退：{}", sysBomChildG.getMaterialName(), should, actual, resultNum);
                                if (resultNum > 0) {
                                    /*退次*/
                                    PickData pickData2 = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChildG, resultNum * GP);
                                    KingdeeResult kingdeeResult2 = this.kingdeeUtils.addPick(pickData2);
                                    if (kingdeeResult2.getStatusCode() == 200) {
                                        saveMaterialRecord(oldWorkPlan, sysBomChildG, -resultNum * GP, pickData2, kingdeeResult2, false);
                                    }


                                } else {
                                    log.error("料号：{}，料名：{}无需退料", sysBomChildG.getMaterialId(), sysBomChildG.getMaterialName());
                                    log.error("料号：{}，料名：{}无需退料", sysBomChildY.getMaterialId(), sysBomChildY.getMaterialName());
                                }
                            } else if (
                                    sysBomChildY.getMaterialId().equals(sysBomChild.getMaterialId())
                                            && (!sysBomChildY.getMaterialId().equals("7.Y13A1A000001")
                                            && !sysBomChildY.getMaterialId().equals("7.Y18A1A000001")
                                            && !sysBomChildY.getMaterialId().equals("7.Y11A1A000349")
                                            && !sysBomChildY.getMaterialId().equals("7.Y11A1A100120")
                                            && !sysBomChildY.getMaterialId().equals("7.Y13A1A000002")
                                    )) {
                                YP = totalYS / totalS;
                                GP = totalGS / totalS;
                                if (sysProductRecord.isTwoWeight()) {
                                    if (sysBomChild.getMaterialId().equals("7.Y13A1A000001")
                                            || sysBomChild.getMaterialId().equals("7.Y13A1A000002")
                                            || sysBomChild.getMaterialId().equals("7.Y18A1A000001")
                                            || sysBomChild.getMaterialId().equals("7.Y11A1A100120")
                                            || sysBomChild.getMaterialId().equals("7.Y11A1A000349")) {
                                        log.error("2称1");
                                        should = 0;
                                        actual = sysProductRecord.getEndWeight1().doubleValue();
                                    } else {
                                        log.error("2称2");
                                        should = 0;
                                        actual = sysProductRecord.getEndWeight2().doubleValue();
                                    }

                                }else   if (sysProductRecord.isHasWeight()) {
                                    actual = sysProductRecord.getEndWeight1().doubleValue();
                                    should = 0;
                                } else {
                                    should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                                    actual = sysBomChild.getHasGetNum();
                                }
                                double resultNum = actual - should;
                                log.error("有软胶物料：{},应发：{},实发：{},退：{}", sysBomChild.getMaterialName(), should, actual, resultNum);

                                if (resultNum > 0) {
                                    /*退原料*/
                                    if (sysBomChildY.getMaterialId().startsWith("7.Y")) {
                                        PickData pickData = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChildY, resultNum * YP);
                                        KingdeeResult kingdeeResult = this.kingdeeUtils.addPick(pickData);
                                        if (kingdeeResult.getStatusCode() == 200) {
                                            saveMaterialRecord(oldWorkPlan, sysBomChildY, -resultNum * YP, pickData, kingdeeResult, false);
                                        }
                                    } else {
                                        PickData pickData = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChild, resultNum);
                                        KingdeeResult kingdeeResult = this.kingdeeUtils.addPick(pickData);
                                        if (kingdeeResult.getStatusCode() == 200) {
                                            saveMaterialRecord(oldWorkPlan, sysBomChild, -resultNum, pickData, kingdeeResult, false);
                                        }
                                    }

                                } else {
                                    log.error("料号：{}，料名：{}无需退料", sysBomChildG.getMaterialId(), sysBomChildG.getMaterialName());
                                    log.error("料号：{}，料名：{}无需退料", sysBomChildY.getMaterialId(), sysBomChildY.getMaterialName());
                                }
                            } else {
                                double resultNum = actual - should;
                                log.error("物料原料1：{},应发：{},实发：{},退：{}", sysBomChild.getMaterialName(), should, actual, resultNum);
                                if (resultNum > 0) {
                                    log.error("不包括次料退");
                                    PickData pickData = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChild, resultNum);
                                    KingdeeResult kingdeeResult = this.kingdeeUtils.addPick(pickData);
                                    if (kingdeeResult.getStatusCode() == 200) {
                                        saveMaterialRecord(oldWorkPlan, sysBomChild, -resultNum, pickData, kingdeeResult, false);
                                    }

                                } else {
                                    log.error("料号2：{}，料名：{}无需退料", sysBomChild.getMaterialId(), sysBomChild.getMaterialName());
                                }
                            }
                        } else {

                            if (sysBomChild.getMaterialId().startsWith("7.Y")) {
                                if (sysProductRecord.isTwoWeight()) {
                                    if (sysBomChild.getMaterialId().equals("7.Y13A1A000001")
                                            || sysBomChild.getMaterialId().equals("7.Y13A1A000002")
                                            || sysBomChild.getMaterialId().equals("7.Y18A1A000001")
                                            || sysBomChild.getMaterialId().equals("7.Y11A1A100120")
                                            || sysBomChild.getMaterialId().equals("7.Y11A1A000349")) {
                                        log.error("2称1");
                                        should = 0;
                                        actual = sysProductRecord.getEndWeight1().doubleValue();
                                    } else {
                                        log.error("2称2");
                                        should = 0;
                                        actual = sysProductRecord.getEndWeight2().doubleValue();
                                    }

                                } else if (sysProductRecord.isHasWeight()) {
                                    log.error("1称");
                                    should = 0;
                                    actual = sysProductRecord.getEndWeight1().doubleValue();
                                } else {
                                    log.error("0称");
                                    should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                                    actual = sysBomChild.getHasGetNum();
                                }
                            } else {
                                should = sysBomChild.getUnitNum().doubleValue() * sysProductRecord.getTotalCount();
                                actual = sysBomChild.getHasGetNum();
                            }
                            double resultNum = actual - should;
                            log.error("物料1：{},应发1：{},实发1：{},退：{}", sysBomChild.getMaterialName(), should, actual, resultNum);
                            if (resultNum > 0) {
                                log.error("不包括次料退");
                                PickData pickData = this.kingdeeUtils.materialUntilBack(oldWorkPlan, sysBomChild, resultNum);
                                KingdeeResult kingdeeResult = this.kingdeeUtils.addPick(pickData);
                                if (kingdeeResult.getStatusCode() == 200) {
                                    saveMaterialRecord(oldWorkPlan, sysBomChild, -resultNum, pickData, kingdeeResult, false);
                                }
                            } else {
                                log.error("料号：{}，料名：{}无需退料", sysBomChild.getMaterialId(), sysBomChild.getMaterialName());
                            }
                        }

                    }

                    return ResultTool.success();

                    /*更新当前生产工单状态*/


                }

            }
        }

        return null;
    }

    @Autowired
    SysMaterialRecordService sysMaterialRecordService;
    @Autowired
    KingdeeUtils kingdeeUtils;


    @Autowired
    SysBadRecordService sysBadRecordService;

    int getBadNum(SysProductRecord sysProductRecord) {
        if (sysProductRecord.getActualStartTime() == null) {
            return 0;
        }
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_BAD_RECORD.WORK_PLAN_ID.eq(sysProductRecord.getWorkPlanId()));
        queryWrapper.select(sum(SYS_BAD_RECORD.NUM).as("num"));
        SysBadRecord sysBadRecord = this.sysBadRecordService.getOne(queryWrapper);
        System.out.println("SysBad:" + sysBadRecord);
        return sysBadRecord == null ? 0 : sysBadRecord.getNum();
    }

    void saveMaterialRecord(SysWorkPlan sysWorkPlan, SysBomChild sysBomChild, double fqty, PickData pickData, KingdeeResult kingdeeResult, boolean type) {
        log.error("SBom:{}", sysBomChild);
        Date now = new Date();
        LocalDate localDate = LocalDate.now();
        int currentHour = now.getHours();
        String shift = null;
        if (currentHour >= 8 && currentHour < 20) {
            shift = "白班";
        } else {
            shift = "夜班";
        }
        if (currentHour < 8) {
            localDate = localDate.minusDays(1);
        }
        Date fdate = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        SysMaterialRecord sysMaterialRecord = new SysMaterialRecord();
        String id = fromDateToString("yyyyMMdd", fdate)
                + sysWorkPlan.getWorkPlanId()
                + sysBomChild.getMaterialId()
                + sysWorkPlan.getMachineName()
                + fromDateToString("yyyyMMddHHmmss", fdate);
        sysMaterialRecord.setId(UUID.randomUUID().toString());
        sysMaterialRecord.setWorkPlanId(sysWorkPlan.getWorkPlanId());
        sysMaterialRecord.setMachineName(sysWorkPlan.getMachineName());
        sysMaterialRecord.setOperationUserId("SYSTEM1");
        sysMaterialRecord.setOperationUserName("SYSTEM1");
        sysMaterialRecord.setProductDate(fdate);
        sysMaterialRecord.setMaterialId(sysBomChild.getMaterialId());
        sysMaterialRecord.setMaterialName(sysBomChild.getMaterialName());
        sysMaterialRecord.setBomId(sysBomChild.getBomId());
        sysMaterialRecord.setMaterialRecord(JSONObject.toJSONString(pickData));
        sysMaterialRecord.setCreateTime(new Date());
        sysMaterialRecord.setNum(fqty);
        sysMaterialRecord.setUnitName(sysBomChild.getUnitName());
        sysMaterialRecord.setShift(shift);
        sysMaterialRecord.setType(type);
        if (kingdeeResult.getStatusCode() == 200) {
            sysMaterialRecord.setHasGet(true);
            JSONObject jsonObject = JSONObject.parseObject(kingdeeResult.getData());
            log.error("JSONOBject:{}", jsonObject);
            try {
                sysMaterialRecord.setKingId(jsonObject.getString("BillNo"));
                sysMaterialRecord.setResultIntId(jsonObject.getString("BillInterID"));
            } catch (Exception e) {

            }
        }
        this.sysMaterialRecordService.save(sysMaterialRecord);
    }

    @Autowired
    SysWeightPlcService sysWeightPlcService;
    @Autowired
    SysWeightDataService sysWeightDataService;

    public SysProductRecord getWeightDataEnd(SysMachinePlc sysMachinePlc, SysProductRecord sysProductRecord) {
        if (sysMachinePlc.isHasWeight()) {
            String weightId1 = null;
            String weightId2 = null;
            if (sysMachinePlc.isHasTwoWeight()) {
                weightId1 = sysMachinePlc.getWeightId1();
                weightId2 = sysMachinePlc.getWeightId2();
            } else {
                weightId2 = "0";
                weightId1 = sysMachinePlc.getWeightId1();
            }
            String sid = this.getSid();
            System.out.println("Sid:" + sid);
            RestTemplate restTemplate = new RestTemplate();
            String machineArea = sysProductRecord.getMachineArea().split("区域")[0];
            QueryWrapper queryWrapper = QueryWrapper.create();
            queryWrapper.where(SYS_WEIGHT_PLC.NAME.eq(machineArea));
            queryWrapper.limit(1);
            SysWeightPlc sysWeightPlc = this.sysWeightPlcService.getOne(queryWrapper);

            String plcDeviceId = String.valueOf(sysWeightPlc.getDeviceId());
            String baseUrl = "https://api.123321yun.com/device/ex/getDetail?deviceId=%s";
            String url = String.format(baseUrl, plcDeviceId);
            System.out.println("Url:" + url);
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
            headers.setContentType(type);
            headers.set("__sid", sid);
            HttpEntity httpEntity = new HttpEntity<>(headers);
            ResponseEntity<Object> responseEntity = restTemplate.postForEntity(url, httpEntity, Object.class);
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(responseEntity.getBody());
            System.out.println("Result:" + jsonObject);
            long sleepTime = 10;
            if (jsonObject.getString("code").equals("200.0")) {
                SysPlc sysPlc = jsonObject.getObject("data", SysPlc.class);
                log.error("SYSPLC:{}", sysPlc);
                JSONArray jsonObject1 = JSON.parseArray(sysPlc.getParamsUp());
                List<SysWeightData> sysWeightDataList = new ArrayList<>();
                for (Object object : jsonObject1) {
                    SysWeightData sysWeightData = new SysWeightData();
                    Paramsup paramsup = JSONObject.parseObject(JSONObject.toJSONString(object), Paramsup.class);
                    String machineNo = paramsup.getName().split("#")[0];
                    String machineName = sysWeightPlc.getName() + machineNo;
                    sysWeightData.setMachineName(machineName);

                    sysWeightData.setNum(BigDecimal.valueOf(Double.parseDouble(StringUtils.isNotBlank(paramsup.getValue())?paramsup.getValue():"0")));
                    sysWeightData.setUnit(paramsup.getUnit());
                    sysWeightData.setWorkPlanId(sysProductRecord.getWorkPlanId());
                    sysWeightData.setProductRecordId(sysProductRecord.getId());
//                    sysWeightData.setId(String.valueOf(paramsup.getId()));
                    if (weightId1.equals(machineNo)) {
                        log.error("Machine:{}", machineNo);
                        boolean result = this.sysWeightDataService.save(sysWeightData);
                        if (result) {
                            sysProductRecord.setEndWeight1(BigDecimal.valueOf(Double.parseDouble(StringUtils.isNotBlank(paramsup.getValue())?paramsup.getValue():"0")));
                        }
                    }
                    if (sysMachinePlc.isHasTwoWeight()) {
                        if (weightId2.equals(machineNo)) {
                            boolean result = this.sysWeightDataService.save(sysWeightData);
                            if (result) {
                                sysProductRecord.setEndWeight2(BigDecimal.valueOf(Double.parseDouble(StringUtils.isNotBlank(paramsup.getValue())?paramsup.getValue():"0")));
                            }
                        }
                    }

                }
            }

        } else {
            sysProductRecord.setHasWeight(false);
            sysProductRecord.setTwoWeight(false);
        }
        return sysProductRecord;
    }

    public void saveProductNight(SysProductRecord sysProductRecord) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        SysProductRecordShift sysProductRecordShift = objectMapper.convertValue(sysProductRecord, SysProductRecordShift.class);
        sysProductRecordShift.setShift("夜班");
        String productRecordId = sysProductRecord.getId();
        sysProductRecordShift.setId(UUID.randomUUID().toString() + "-lightShift");
        SysProductRecordShift lightShiftProduct = this.sysProductRecordShiftService.getById(sysProductRecordShift.getId());
        if (lightShiftProduct != null) {
            SysProductRecordShift nightShiftProduct = sysProductRecordShift;
            int totalGood = sysProductRecord.getGoodNum();
            int totalBad = 0;
            try {
                totalBad = sysProductRecord.getBadNum();
            } catch (Exception e) {

            }
            int totalCount = sysProductRecord.getTotalCount();
            int nightGood = totalGood - lightShiftProduct.getGoodNum();
            try {
                int nightBad = totalBad - lightShiftProduct.getBadNum();
                nightShiftProduct.setBadNum(nightBad);
            } catch (Exception e) {
                nightShiftProduct.setBadNum(0);
            }

            int nightTotalCount = totalCount - lightShiftProduct.getTotalCount();
            nightShiftProduct.setGoodNum(nightGood);

            nightShiftProduct.setTotalCount(nightTotalCount);
            nightShiftProduct.setShift("夜班");
            nightShiftProduct.setActualStartTime(lightShiftProduct.getActualEndTime());
            nightShiftProduct.setActualEndTime(new Date());
            nightShiftProduct.setEntry(false);

            nightShiftProduct.setId(UUID.randomUUID().toString() + "nightShift");
            LocalDate productDate = LocalDate.now();
            LocalDate yesterday = productDate.minusDays(1);
            QueryWrapper queryWrapper = QueryWrapper.create();
            queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.MACHINE_NAME.eq(sysProductRecord.getMachineName()));
            queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.PRODUCT_ID.eq(sysProductRecord.getProductId()));
            queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.PRODUCT_DATE.eq(yesterday));
            queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.SHIFT.eq("夜班"));
            queryWrapper.orderBy(SYS_PRODUCT_RECORD_SHIFT.ACTUAL_START_TIME, true);
            queryWrapper.limit(1);
            SysProductRecordShift productRecordShift = this.sysProductRecordShiftService.getOne(queryWrapper);
            if (productRecordShift != null) {
                log.error("有尾箱");
                sysProductRecordShift.setLastTailBoxCount(productRecordShift.getNowTailBoxCount());
            } else {
                log.error("没有尾箱");
                sysProductRecordShift.setLastTailBoxCount(0);
            }
            try {

                boolean result = this.sysProductRecordShiftService.save(nightShiftProduct);
            } catch (Exception e) {

            }
        } else {
            sysProductRecordShift.setShift("夜班");
            sysProductRecordShift.setActualEndTime(new Date());
            sysProductRecordShift.setEntry(false);
            sysProductRecordShift.setId(UUID.randomUUID().toString() + "nightShift");
            boolean result = this.sysProductRecordShiftService.save(sysProductRecordShift);
        }

    }

    public void saveProductLight(SysProductRecord sysProductRecord) throws IOException {
        LocalDate productDate = LocalDate.now();
        ObjectMapper objectMapper = new ObjectMapper();
        SysProductRecordShift sysProductRecordShift = objectMapper.convertValue(sysProductRecord, SysProductRecordShift.class);
        sysProductRecordShift.setShift("白班");
        sysProductRecordShift.setActualEndTime(new Date());
        sysProductRecordShift.setEntry(false);
        sysProductRecordShift.setId(UUID.randomUUID().toString());

        LocalDate yesterday = productDate.minusDays(1);
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.MACHINE_NAME.eq(sysProductRecord.getMachineName()));
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.PRODUCT_ID.eq(sysProductRecord.getProductId()));
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.PRODUCT_DATE.eq(yesterday));
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.SHIFT.eq("白班"));
        queryWrapper.orderBy(SYS_PRODUCT_RECORD_SHIFT.ACTUAL_START_TIME, true);
        queryWrapper.limit(1);
        SysProductRecordShift productRecordShift = this.sysProductRecordShiftService.getOne(queryWrapper);
        if (productRecordShift != null) {
            log.error("有尾箱");
            sysProductRecordShift.setLastTailBoxCount(productRecordShift.getNowTailBoxCount());
        } else {
            log.error("没有尾箱");
            sysProductRecordShift.setLastTailBoxCount(0);
        }
        sysProductRecordShift.setProductDate(Date.from(productDate.atStartOfDay(ZoneId.systemDefault()).toInstant()));
        boolean result = this.sysProductRecordShiftService.save(sysProductRecordShift);
    }


}

